﻿using Comm;
using Comm.Helper;
using GalaSoft.MvvmLight.Messaging;
using Kinlo.Drv.Machine;
using Kinlo.Model;
using Kinlo.Repo;
using Newtonsoft.Json;
using S7.Net;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Kinlo.SWDLib;
using System.Windows;
using Kinlo.Drv.Drv.RJShortCirrcuitResult;
using Kinlo.MesCheck;

namespace Kinlo.Core.Service
{
    public class CoreService
    {
        ShortCircuitMachine shortCircuit;
        //自动导出记录定时器
        System.Timers.Timer timer4 = new System.Timers.Timer(10 * 60 * 1000);
        //检查未上传记录定时器
        System.Timers.Timer timer5 = new System.Timers.Timer(5 * 60 * 1000);
        List<string> ReadBeforWeightNodes = new List<string>();
        List<string> ReadCodeNodes = new List<string>();
        List<string> ReadAfterWeightNodes = new List<string>();
        bool isDebug = false;
        System.Timers.Timer timer = new System.Timers.Timer(1000);
        System.Timers.Timer timer2 = new System.Timers.Timer(5000);
        System.Timers.Timer timer3 = new System.Timers.Timer(500);
        object locker = new object();
        object locker2 = new object();
        public ElecBalanceMachine BeforeWeighter;
        public ElecBalanceMachine AfterWeighter;
        AfterWeightFirstRep AFDB = new AfterWeightFirstRep();
        BeforWeightFirstRep BFDB = new BeforWeightFirstRep();
        CodeFirstRep CFDB = new CodeFirstRep();
        CounterRep CNTDB = new CounterRep();
        StatusRep SDB = new StatusRep();
        bool IsDelete = false;
        Plc plc;
        Plc plc2; //报警
        public Boolean MESLoadingUsed = false;
        List<CodeFirst> CodeFirsts = new List<CodeFirst>();
        List<BeforWeightFirst> BeforWeightFirsts = new List<BeforWeightFirst>();
        List<AfterWeightFirst> AfterWeightFirsts = new List<AfterWeightFirst>();
        public int InCount = 0;
        public int OutCount = 0;
        public int OKCount = 0;
        public int NGCount = 0;
        public int DBNo = 11;
        //报警DB号
        public int DBNo1 = 110;

        public KNCScannerMachine FrontScanner;
        public KNCScannerMachine FrontScanner2;

        string StrRegex = "";
        bool IsCheckBarcode = false;
        string PortName = "COM1";
        int BaudRate = 9600;
        int DataBits = 8;
        Parity Parity = Parity.None;
        StopBits StopBits = StopBits.One;
        int SerialPortTimeout = 8000;
        //返回ＰＬＣ结果
        Int16 r0 = 0;
        Int16 r1 = 1;
        Int16 r2 = 2;
        Int16 r3 = 3;
        Int16 r4 = 4;
        string MachineCode = "SecInjection";
        string WorkFlowNo = "WF160910001";
        string StationNo = "15";
        int WorkFlowOrder = 1;

        string Locate = "ZH";
        //string InjType = "YC";
        int clearRecordByAfterDays = 30;

        SerialPort serialPort;
        string ExportPath = @"..\ExportData";
        bool IsTestMode = false;
        private SnowflakeManager _snowflake;

        public CoreService()
        {
            _snowflake = new SnowflakeManager(12);
            try
            {
                timer.Elapsed += Timer_Elapsed;
                bool.TryParse(ConfigurationManager.AppSettings["IsDelete"], out IsDelete);

                bool.TryParse(ConfigurationManager.AppSettings["IsDebug"], out isDebug);
                var ipaddr = "192.168.10.100";
                ipaddr = ConfigurationManager.AppSettings["Ipaddr"];
                int dbno = 0;
                if (int.TryParse(ConfigurationManager.AppSettings["DBNo"], out dbno))
                {
                    DBNo = dbno;
                }
                int dbno1 = 0;
                if (int.TryParse(ConfigurationManager.AppSettings["DBNo1"], out dbno1))
                {
                    DBNo1 = dbno1;
                }
                var exportPath = ConfigurationManager.AppSettings["ExportPath"];
                if (!string.IsNullOrEmpty(exportPath))
                {
                    ExportPath = exportPath;
                }
                plc = new Plc(CpuType.S71500, ipaddr, 0, 0);
                Thread.Sleep(500);
                plc2 = new Plc(CpuType.S71500, ipaddr, 0, 0);
                var FrontScannerIp = "192.168.10.161";
                int FrontScannerIpPort = 9004;
                var frontScannerIp = ConfigurationManager.AppSettings["FrontScannerIp"];
                if (!string.IsNullOrEmpty(frontScannerIp))
                {
                    FrontScannerIp = frontScannerIp;
                }
                var frontScannerIpPort = ConfigurationManager.AppSettings["FrontScannerIpPort"];
                if (!string.IsNullOrEmpty(frontScannerIpPort))
                {
                    var port = 0;
                    if (int.TryParse(frontScannerIpPort, out port))
                    {
                        FrontScannerIpPort = port;
                    }
                }
                FrontScanner = new KNCScannerMachine(FrontScannerIp, FrontScannerIpPort, "1", 1000);
                var FrontScannerIp2 = "192.168.10.162";
                int FrontScannerIpPort2 = 9004;
                var frontScannerIp2 = ConfigurationManager.AppSettings["FrontScannerIp2"];
                if (!string.IsNullOrEmpty(frontScannerIp2))
                {
                    FrontScannerIp2 = frontScannerIp2;
                }
                var frontScannerIpPort2 = ConfigurationManager.AppSettings["FrontScannerIpPort2"];
                if (!string.IsNullOrEmpty(frontScannerIpPort2))
                {
                    var port = 0;
                    if (int.TryParse(frontScannerIpPort2, out port))
                    {
                        FrontScannerIpPort2 = port;
                    }
                }
                FrontScanner2 = new KNCScannerMachine(FrontScannerIp2, FrontScannerIpPort2, "1", 1000);

                PortName = ConfigurationManager.AppSettings["PortName"];
                int buadRate;
                if (int.TryParse(ConfigurationManager.AppSettings["BaudRate"], out buadRate))
                {
                    BaudRate = buadRate;
                }
                int dataBits;
                if (int.TryParse(ConfigurationManager.AppSettings["DataBits"], out dataBits))
                {
                    DataBits = dataBits;
                }
                Parity parity;
                if (Parity.TryParse(ConfigurationManager.AppSettings["Parity"], out parity))
                {
                    Parity = parity;
                }
                StopBits stopBits;
                if (Parity.TryParse(ConfigurationManager.AppSettings["StopBits"], out stopBits))
                {
                    StopBits = stopBits;
                }
                int stimeout;
                if (int.TryParse(ConfigurationManager.AppSettings["SerialPortTimeout"], out stimeout))
                {
                    SerialPortTimeout = stimeout;
                }


                Task.Run(() =>
                {
                    var cnt = CNTDB.GetCounter();
                    if (cnt != null)
                    {
                        InCount = cnt.InCount;
                        OutCount = cnt.OutCount;
                        OKCount = cnt.OKCount;
                        NGCount = cnt.NGCount;
                        Messenger.Default.Send<int>(InCount, "SendINCount");
                        Messenger.Default.Send<int>(OutCount, "SendOutCount");
                        Messenger.Default.Send<int>(OKCount, "SendOKCount");
                        Messenger.Default.Send<int>(NGCount, "SendNGCount");
                    }
                    else
                    {
                        Logger.Info("counter 失败");
                    }
                });


                var regex = ConfigurationManager.AppSettings["Regex"];
                if (string.IsNullOrEmpty(regex))
                {
                    regex = "^[0-9a-zA-Z]";
                }
                StrRegex = regex;

                var isCheckBarcode = ConfigurationManager.AppSettings["IsCheckBarcode"];
                if (string.IsNullOrEmpty(isCheckBarcode))
                {
                    IsCheckBarcode = false;
                }
                else
                {
                    bool.TryParse(isCheckBarcode, out IsCheckBarcode);
                }
                var EquNo = ConfigurationManager.AppSettings["EquNo"];
                if (!string.IsNullOrEmpty(EquNo))
                {
                    GlobalValues.EquNo = EquNo;
                }
                var BatchNo = ConfigurationManager.AppSettings["BatchNo"];
                if (!string.IsNullOrEmpty(BatchNo))
                {
                    GlobalValues.BatchNo = BatchNo;
                }
                var BatchNo1 = ConfigurationManager.AppSettings["BatchNo1"];
                if (!string.IsNullOrEmpty(BatchNo1))
                {
                    GlobalValues.BatchNo1 = BatchNo1;
                }
                Messenger.Default.Send<string>("", "CmdUpdateJDBatchNo");
                var JDBatchNo = ConfigurationManager.AppSettings["JDBatchNo"];
                if (!string.IsNullOrEmpty(JDBatchNo))
                {
                    GlobalValues.JDBatchNo = JDBatchNo;
                }
                var djyWater = ConfigurationManager.AppSettings["DJYWater"];
                if (!string.IsNullOrEmpty(djyWater))
                {
                    GlobalValues.DJYWater = djyWater;
                }
                Messenger.Default.Send<string>("", "CmdUpdateBatchNo");
                var djyHydrofluoric = ConfigurationManager.AppSettings["DJYHydrofluoric"];
                if (!string.IsNullOrEmpty(djyHydrofluoric))
                {
                    GlobalValues.DJYHydrofluoric = djyHydrofluoric;
                }
                var machineCode = ConfigurationManager.AppSettings["MachineCode"];
                if (!string.IsNullOrEmpty(machineCode))
                {
                    MachineCode = machineCode;
                }
                var locate = ConfigurationManager.AppSettings["Locate"];
                if (!string.IsNullOrEmpty(locate))
                {
                    Locate = locate;
                    GlobalValues.Locate = locate;
                }
                var workFlowNo = ConfigurationManager.AppSettings["WorkFlowNo"];
                if (!string.IsNullOrEmpty(workFlowNo))
                {
                    WorkFlowNo = workFlowNo;
                }
                var stationNo = ConfigurationManager.AppSettings["StationNo"];
                if (!string.IsNullOrEmpty(stationNo))
                {
                    StationNo = stationNo;
                }
                var workFlowOrder = ConfigurationManager.AppSettings["WorkFlowOrder"];
                if (!string.IsNullOrEmpty(workFlowOrder))
                {
                    int order = 0;
                    if (int.TryParse(workFlowOrder, out order))
                    {
                        WorkFlowOrder = order;
                    }
                }

                var dataUpload = ConfigurationManager.AppSettings["DataUpload"];
                if (!string.IsNullOrEmpty(dataUpload))
                {
                    bool result = false;
                    if (bool.TryParse(dataUpload, out result))
                    {
                        GlobalValues.DataUpload = result;
                    }
                }

                var injValStd = ConfigurationManager.AppSettings["InjValStd"];
                if (!string.IsNullOrEmpty(injValStd))
                {
                    float result = 0.0f;
                    if (float.TryParse(injValStd, out result))
                    {
                        GlobalValues.InjValStd = result;
                    }
                }
                var injValMin = ConfigurationManager.AppSettings["InjValMin"];
                if (!string.IsNullOrEmpty(injValMin))
                {
                    float result = 0.0f;
                    if (float.TryParse(injValMin, out result))
                    {
                        GlobalValues.InjValMin = result;
                    }
                }
                var injValMax = ConfigurationManager.AppSettings["InjValMax"];
                if (!string.IsNullOrEmpty(machineCode))
                {
                    float result = 0.0f;
                    if (float.TryParse(injValMax, out result))
                    {
                        GlobalValues.InjValMax = result;
                    }
                }
                var injValTotal = ConfigurationManager.AppSettings["InjValTotalStd"];
                if (!string.IsNullOrEmpty(injValTotal))
                {
                    float result = 0.0f;
                    if (float.TryParse(injValTotal, out result))
                    {
                        GlobalValues.InjValTotalStd = result;
                    }
                    else
                    {
                        Logger.Info(string.Format("InjValTotal 参数设定异常"));
                    }
                }
                var injValTotalMin = ConfigurationManager.AppSettings["InjValTotalMin"];
                if (!string.IsNullOrEmpty(injValTotalMin))
                {
                    float result = 0.0f;
                    if (float.TryParse(injValTotalMin, out result))
                    {
                        GlobalValues.InjValTotalMin = result;
                    }
                    else
                    {
                        Logger.Info(string.Format("InjValTotalMin 参数设定异常"));
                    }
                }
                var injValTotalMax = ConfigurationManager.AppSettings["InjValTotalMax"];
                if (!string.IsNullOrEmpty(injValTotalMax))
                {
                    float result = 0.0f;
                    if (float.TryParse(injValTotalMax, out result))
                    {
                        GlobalValues.InjValTotalMax = result;
                    }
                    else
                    {
                        Logger.Info(string.Format("InjValTotalMax 参数设定异常"));
                    }
                }

                #region 液矢量
                var VectorMin = ConfigurationManager.AppSettings["VectorMin"];
                if (!string.IsNullOrEmpty(VectorMin))
                {
                    float result = 0.0f;
                    if (float.TryParse(VectorMin, out result))
                    {
                        GlobalValues.VectorMin = result;
                    }
                    else
                    {
                        Logger.Info(string.Format("VectorMin 参数设定异常"));
                    }
                }
                var VectorMax = ConfigurationManager.AppSettings["VectorMax"];
                if (!string.IsNullOrEmpty(VectorMax))
                {
                    float result = 0.0f;
                    if (float.TryParse(VectorMax, out result))
                    {
                        GlobalValues.VectorMax = result;
                    }
                    else
                    {
                        Logger.Info(string.Format("VectorMax 参数设定异常"));
                    }
                }
                #endregion

                var bforeWeightIP = ConfigurationManager.AppSettings["BeforeWeightIP"];
                if (!string.IsNullOrEmpty(bforeWeightIP))
                {
                    GlobalValues.BeforeWeightIP = bforeWeightIP;
                }
                var beforeWeightIPpPort = ConfigurationManager.AppSettings["BeforeWeightIPpPort"];
                if (!string.IsNullOrEmpty(beforeWeightIPpPort))
                {
                    int result = 0;
                    if (int.TryParse(beforeWeightIPpPort, out result))
                    {
                        GlobalValues.BeforeWeightIPpPort = result;
                    }
                }
                var afterWeightIP = ConfigurationManager.AppSettings["AfterWeightIP"];
                if (!string.IsNullOrEmpty(afterWeightIP))
                {
                    GlobalValues.AfterWeightIP = afterWeightIP;
                }
                var afterWeightIPPort = ConfigurationManager.AppSettings["AfterWeightIPPort"];
                if (!string.IsNullOrEmpty(afterWeightIPPort))
                {
                    int result = 0;
                    if (int.TryParse(afterWeightIPPort, out result))
                    {
                        GlobalValues.AfterWeightIPPort = result;
                    }
                }

                //var injType = ConfigurationManager.AppSettings["InjType"];
                //if (!string.IsNullOrEmpty(injType))
                //{
                //    InjType = injType;
                //}
                GlobalValues.OpType = "YC";
                var opType = ConfigurationManager.AppSettings["OpType"];
                if (!string.IsNullOrEmpty(opType))
                {
                    GlobalValues.OpType = opType;
                }
                GlobalValues.Passwd = "123456";
                var SettingPasswd = ConfigurationManager.AppSettings["SettingPasswd"];
                if (!string.IsNullOrEmpty(SettingPasswd))
                {
                    GlobalValues.Passwd = SettingPasswd;
                }

                var productModel = ConfigurationManager.AppSettings["ProductModel"];
                if (!string.IsNullOrEmpty(productModel))
                {
                    GlobalValues.ProductModel = productModel;
                }
                var moNumber = ConfigurationManager.AppSettings["MoNumber"];
                if (!string.IsNullOrEmpty(moNumber))
                {
                    GlobalValues.MoNumber = moNumber;
                }
                var mesurl = ConfigurationManager.AppSettings["MESUrl"];
                if (!string.IsNullOrEmpty(mesurl))
                {
                    GlobalValues.MESUrl = mesurl;
                }
                var groupName = ConfigurationManager.AppSettings["GroupName"];
                if (!string.IsNullOrEmpty(groupName))
                {
                    GlobalValues.GroupName = groupName;
                }
                var groupCode = ConfigurationManager.AppSettings["GroupCode"];
                GlobalValues.GroupCode = "";
                if (!string.IsNullOrEmpty(groupCode))
                {
                    var code = groupCode.Split('|');

                    if (GlobalValues.OpType.ToUpper() == "YC")
                    {
                        if (code.Length > 0)
                        {
                            GlobalValues.GroupCode = code[0];
                        }
                    }
                    else if (GlobalValues.OpType.ToUpper() == "EC")
                    {
                        if (code.Length > 1)
                        {
                            GlobalValues.GroupCode = code[1];
                        }
                    }
                    else if (GlobalValues.OpType.ToUpper() == "SC")
                    {
                        if (code.Length > 1)
                        {
                            GlobalValues.GroupCode = code[2];
                        }
                    }
                }
                Messenger.Default.Send<string>("", "UpdateUIGloableValues");
                var itemNo = ConfigurationManager.AppSettings["ItemNo"];
                if (!string.IsNullOrEmpty(itemNo))
                {
                    GlobalValues.ItemNo = itemNo;
                }
                var itemBatchNo = ConfigurationManager.AppSettings["ItemBatchNo"];
                if (!string.IsNullOrEmpty(itemBatchNo))
                {
                    GlobalValues.ItemBatchNo = itemBatchNo;
                }
                var itemNum = ConfigurationManager.AppSettings["ItemNum"];
                if (!string.IsNullOrEmpty(itemNum))
                {
                    GlobalValues.ItemNum = itemNum;
                }
                Messenger.Default.Send<string>("", "CmdUpdateItemNo");
                var enableVarInj = ConfigurationManager.AppSettings["EnableVarInj"];
                if (!string.IsNullOrEmpty(enableVarInj))
                {
                    bool enVarInj = false;
                    if (bool.TryParse(enableVarInj, out enVarInj))
                    {
                        GlobalValues.EnableVarInj = enVarInj;
                    }
                    else
                    {
                        Logger.Info(string.Format("EnableVarInj 参数 转换失败 {0}", enableVarInj));
                    }
                }
                var mesonoff = ConfigurationManager.AppSettings["MesOnOff"];
                if (!string.IsNullOrEmpty(mesonoff))
                {
                    bool val = false;
                    if (bool.TryParse(mesonoff, out val))
                    {
                        GlobalValues.MesOnOff = val;
                    }
                    else
                    {
                        Logger.Info(string.Format("MesOnOff 参数 转换失败 {0}", mesonoff));
                    }
                }

                var mesGroupCheckonoff = ConfigurationManager.AppSettings["MesGroupCheckOnOff"];
                if (!string.IsNullOrEmpty(mesGroupCheckonoff))
                {
                    bool val = false;
                    if (bool.TryParse(mesGroupCheckonoff, out val))
                    {
                        GlobalValues.MesGroupCheckOnOff = val;
                    }
                    else
                    {
                        Logger.Info(string.Format("MesGroupCheckOnOff 参数 转换失败 {0}", mesGroupCheckonoff));
                    }
                }



                var rework = ConfigurationManager.AppSettings["Rework"];
                if (!string.IsNullOrEmpty(rework))
                {
                    bool val = false;
                    if (bool.TryParse(rework, out val))
                    {
                        GlobalValues.Rework = val;
                    }
                    else
                    {
                        Logger.Info(string.Format("Rework 参数 转换失败 {0}", rework));
                    }
                }
                var testType = ConfigurationManager.AppSettings["TestType"];
                if (!string.IsNullOrEmpty(testType))
                {
                    if (int.TryParse(testType, out var val))
                    {
                        GlobalValues.TestType = val;
                    }
                    else
                    {
                        Logger.Info(string.Format("TestType 参数 转换失败 {0}", testType));
                    }
                }

                var day = ConfigurationManager.AppSettings["ClearRecordByAfterDay"];
                if (!string.IsNullOrEmpty(day))
                {
                    var days = 0;
                    if (int.TryParse(day, out days))
                    {
                        clearRecordByAfterDays = days;
                    }
                }
                var testMode = ConfigurationManager.AppSettings["IsTestMode"];
                if (!string.IsNullOrEmpty(testMode))
                {
                    bool.TryParse(testMode, out IsTestMode);
                }

                var enableBeforeCheck = ConfigurationManager.AppSettings["EnableBeforeInjectCheck"];
                if (!string.IsNullOrEmpty(enableBeforeCheck))
                {
                    bool enVarInj = false;
                    if (bool.TryParse(enableBeforeCheck, out enVarInj))
                    {
                        GlobalValues.EnableBeforeInjectCheck = enVarInj;
                    }
                    else
                    {
                        Logger.Info(string.Format("EnableBeforeInjectCheck 参数 转换失败 {0}", enableVarInj));
                    }
                }
                var enableAfterCheck = ConfigurationManager.AppSettings["EnableAfterInjectCheck"];
                if (!string.IsNullOrEmpty(enableAfterCheck))
                {
                    bool enVarInj = false;
                    if (bool.TryParse(enableAfterCheck, out enVarInj))
                    {
                        GlobalValues.EnableAfterInjectCheck = enVarInj;
                    }
                    else
                    {
                        Logger.Info(string.Format("EnableAfterInjectCheck 参数 转换失败 {0}", enableVarInj));
                    }
                }
                var beforeWeightMin = ConfigurationManager.AppSettings["BeforeWeightMin"];
                if (!string.IsNullOrEmpty(beforeWeightMin))
                {
                    float result = 0.0f;
                    if (float.TryParse(beforeWeightMin, out result))
                    {
                        GlobalValues.BeforeWeightMin = result;
                    }
                    else
                    {
                        Logger.Info(string.Format("BeforeWeightMin 参数设定异常"));
                    }
                }
                var beforeWeightMax = ConfigurationManager.AppSettings["BeforeWeightMax"];
                if (!string.IsNullOrEmpty(beforeWeightMax))
                {
                    float result = 0.0f;
                    if (float.TryParse(beforeWeightMax, out result))
                    {
                        GlobalValues.BeforeWeightMax = result;
                    }
                    else
                    {
                        Logger.Info(string.Format("BeforeWeightMax 参数设定异常"));
                    }
                }
                var afterWeightMin = ConfigurationManager.AppSettings["AfterWeightMin"];
                if (!string.IsNullOrEmpty(afterWeightMin))
                {
                    float result = 0.0f;
                    if (float.TryParse(afterWeightMin, out result))
                    {
                        GlobalValues.AfterWeightMin = result;
                    }
                    else
                    {
                        Logger.Info(string.Format("AfterWeightMin 参数设定异常"));
                    }
                }

                var afterWeightMax = ConfigurationManager.AppSettings["AfterWeightMax"];
                if (!string.IsNullOrEmpty(afterWeightMax))
                {
                    float result = 0.0f;
                    if (float.TryParse(afterWeightMax, out result))
                    {
                        GlobalValues.AfterWeightMax = result;
                    }
                    else
                    {
                        Logger.Info(string.Format("AfterWeightMax 参数设定异常"));
                    }
                }
                try
                {
                    if (GlobalValues.TestType == 1)
                    {
                        serialPort = new SerialPort(PortName, BaudRate, Parity, DataBits, StopBits);
                        serialPort.Open();
                        Logger.Info(serialPort.IsOpen ? "短路测试仪连接成功!1" : "短路测试仪连接失败1");
                    }
                    else
                    {
                        shortCircuit = new ShortCircuitMachine(PortName, BaudRate, Parity, DataBits, StopBits, SerialPortTimeout);
                        Logger.Info(shortCircuit.Conncet() ? "短路测试仪连接成功!2" : "短路测试仪连接失败2");
                    }
                }
                catch { }

                BeforeWeighter = new ElecBalanceMachine(GlobalValues.BeforeWeightIP, GlobalValues.BeforeWeightIPpPort, "1");
                AfterWeighter = new ElecBalanceMachine(GlobalValues.AfterWeightIP, GlobalValues.AfterWeightIPPort, "2");

                timer2.Elapsed += Timer2_Elapsed;
                timer2.Enabled = true;

                CFDB.ClearRecordsByDay(clearRecordByAfterDays);

                timer4.Elapsed += Timer4_Elapsed; ;
                timer4.Enabled = true;
                timer5.Elapsed += Timer5_Elapsed;
                timer5.Enabled = true;
                Task.Run(() =>
                {
                    Thread.Sleep(10000);
                    Timer4_Elapsed(null, null);
                    Timer5_Elapsed(null, null);

                });
                InitErrorMsg();
                Messenger.Default.Send<string>("", "ChangeTitle");
            }
            catch (Exception ex)
            {
                Logger.Info(string.Format("精朗称重软件 {0}", ex.Message));
            }
            finally
            {
                if (Loaded != null)
                {
                    try
                    {
                        Loaded.Invoke(this, null);
                    }
                    catch { }
                }
            }
        }
        public static event EventHandler<object> Loaded;
        void InitErrorMsg()
        {
            ErrorMsg = new List<string>() {
                "急停按下",
                "称重软件没有打开。。。",
                "cv_入料扫码阻挡异常",
                "cv_入料扫码定位异常",
                "cv_测短路阻挡异常",
                "cv_测短路定位异常",
                "cv_前称重阻挡异常",
                "cv_前称重护边异常",
                "cv_前称重举升异常",
                "cv_注液上下料夹爪异常",
                "cv_A工位注液伸缩异常",
                "cv_A工位注液举升异常",
                "cv_A工位上杯压杆1异常",
                "cv_A工位上杯压杆2异常",
                "cv_A工位下杯压杆异常",
                "cv_A工位吸残液升降异常",
                "cv_A工位密封圈异常",
                "cv_A工位吸残液异常",
                "cv_A工位高压异常",
                "cv_A工位大气异常",
                "cv_A工位高真空异常",
                "cv_B工位注液伸缩异常",
                "cv_B工位注液举升异常",
                "cv_B工位上杯压杆1异常",
                "cv_B工位上杯压杆2异常",
                "cv_B工位下杯压杆异常",
                "cv_B工位吸残液升降异常",
                "cv_B工位密封圈异常",
                "cv_B工位吸残液异常",
                "cv_B工位高压异常",
                "cv_B工位大气异常",
                "cv_B工位高真空异常",
                "cv_C工位注液伸缩异常",
                "cv_C工位注液举升异常",
                "cv_C工位上杯压杆1异常",
                "cv_C工位上杯压杆2异常",
                "cv_C工位下杯压杆异常",
                "cv_C工位吸残液升降异常",
                "cv_C工位密封圈异常",
                "cv_C工位吸残液异常",
                "cv_C工位高压异常",
                "cv_C工位大气异常",
                "cv_C工位高真空异常",
                "cv_D工位注液伸缩异常",
                "cv_D工位注液举升异常",
                "cv_D工位上杯压杆1异常",
                "cv_D工位上杯压杆2异常",
                "cv_D工位下杯压杆异常",
                "cv_D工位吸残液升降异常",
                "cv_D工位密封圈异常",
                "cv_D工位吸残液异常",
                "cv_D工位高压异常",
                "cv_D工位大气异常",
                "cv_D工位高真空异常",
                "cv_E工位注液伸缩异常",
                "cv_E工位注液举升异常",
                "cv_E工位上杯压杆1异常",
                "cv_E工位上杯压杆2异常",
                "cv_E工位下杯压杆异常",
                "cv_E工位吸残液升降异常",
                "cv_E工位密封圈异常",
                "cv_E工位吸残液异常",
                "cv_E工位高压异常",
                "cv_E工位大气异常",
                "cv_E工位高真空异常",
                "cv_F工位注液伸缩异常",
                "cv_F工位注液举升异常",
                "cv_F工位上杯压杆1异常",
                "cv_F工位上杯压杆2异常",
                "cv_F工位下杯压杆异常",
                "cv_F工位吸残液升降异常",
                "cv_F工位密封圈异常",
                "cv_F工位吸残液异常",
                "cv_F工位高压异常",
                "cv_F工位大气异常",
                "cv_F工位高真空异常",
                "cv_G工位注液伸缩异常",
                "cv_G工位注液举升异常",
                "cv_G工位上杯压杆1异常",
                "cv_G工位上杯压杆2异常",
                "cv_G工位下杯压杆异常",
                "cv_G工位吸残液升降异常",
                "cv_G工位密封圈异常",
                "cv_G工位吸残液异常",
                "cv_G工位高压异常",
                "cv_G工位大气异常",
                "cv_G工位高真空异常",
                "cv_后称重阻挡异常",
                "cv_后称重护边异常",
                "cv_后称重举升异常",
                "cv_A工位下杯压杆异常2",
                "cv_B工位下杯压杆异常2",
                "cv_C工位下杯压杆异常2",
                "cv_D工位下杯压杆异常2",
                "cv_E工位下杯压杆异常2",
                "cv_F工位下杯压杆异常2",
                "cv_G工位下杯压杆异常2",
                "异常96",
                "异常97",
                "异常98",
                "异常99",
                "异常100",
                "异常101",
                "异常102",
                "异常103",
                "异常104",
                "异常105",
                "异常106",
                "异常107",
                "异常108",
                "异常109",
                "异常110",
                "异常111",
                "异常112",
                "异常113",
                "异常114",
                "异常115",
                "异常116",
                "异常117",
                "异常118",
                "异常119",
                "异常120",
                "异常121",
                "异常122",
                "异常123",
                "异常124",
                "异常125",
                "异常126",
                "异常127",
                "异常128",
                "异常129",
                "异常130",
                "异常131",
                "异常132",
                "异常133",
                "异常134",
                "异常135",
                "异常136",
                "异常137",
                "异常138",
                "异常139",
                "异常140",
                "异常141",
                "异常142",
                "异常143",
                "异常144",
                "异常145",
                "异常146",
                "异常147",
                "异常148",
                "异常149",
                "异常150",
                "异常151",
                "异常152",
                "异常153",
                "异常154",
                "异常155",
                "异常156",
                "异常157",
                "异常158",
                "异常159",
                "异常160",
                "异常161",
                "异常162",
                "异常163",
                "异常164",
                "异常165",
                "异常166",
                "异常167",
                "异常168",
                "异常169",
                "异常170",
                "异常171",
                "异常172",
                "异常173",
                "异常174",
                "异常175",
                "异常176",
                "异常177",
                "异常178",
                "异常179",
                "异常180",
                "异常181",
                "异常182",
                "异常183",
                "异常184",
                "异常185",
                "异常186",
                "异常187",
                "异常188",
                "异常189",
                "异常190",
                "异常191",
                "异常192",
                "异常193",
                "异常194",
                "异常195",
                "异常196",
                "异常197",
                "异常198",
                "异常199",
                "异常200",
                "异常201",
                "异常202",
                "异常203",
                "异常204",
                "异常205",
                "异常206",
                "异常207",
                "异常208",
                "异常209",
                "异常210",
                "异常211",
                "异常212",
                "异常213",
                "异常214",
                "异常215",
                "异常216",
                "异常217",
                "异常218",
                "异常219",
                "异常220",
                "异常221",
                "异常222",
                "异常223",
                "异常224",
                "异常225",
                "异常226",
                "异常227",
                "异常228",
                "异常229",
                "异常230",
                "异常231",
                "异常232",
                "异常233",
                "异常234",
                "异常235",
                "异常236",
                "异常237",
                "异常238",
                "异常239",
                "异常240",
                "异常241",
                "异常242",
                "异常243",
                "异常244",
                "异常245",
                "异常246",
                "异常247",
                "异常248",
                "异常249",
                "异常250",
                "异常251",
                "异常252",
                "异常253",
                "异常254",
                "异常255",
                "异常256",
                "异常257",
                "异常258",
                "异常259",
                "异常260",
                "异常261",
                "异常262",
                "异常263",
                "异常264",
                "异常265",
                "异常266",
                "异常267",
                "异常268",
                "异常269",
                "异常270",
                "异常271",
                "异常272",
                "异常273",
                "异常274",
                "异常275",
                "异常276",
                "异常277",
                "异常278",
                "异常279",
                "异常280",
                "异常281",
                "异常282",
                "异常283",
                "异常284",
                "异常285",
                "异常286",
                "异常287",
                "异常288",
                "异常289",
                "异常290",
                "异常291",
                "异常292",
                "异常293",
                "异常294",
                "异常295",
                "异常296",
                "异常297",
                "异常298",
                "异常299",
                "异常300",
                "异常301",
                "异常302",
                "异常303",
                "异常304",
                "异常305",
                "异常306",
                "异常307",
                "异常308",
                "异常309",
                "异常310",
                "异常311",
                "异常312",
                "异常313",
                "异常314",
                "异常315",
                "异常316",
                "异常317",
                "异常318",
                "异常319",
                "异常320",
                "异常321",
                "异常322",
                "异常323",
                "异常324",
                "异常325",
                "异常326",
                "异常327",
                "异常328",
                "异常329",
                "异常330",
                "异常331",
                "异常332",
                "异常333",
                "异常334",
                "异常335",
                "异常336",
                "异常337",
                "异常338",
                "异常339",
                "异常340",
                "异常341",
                "异常342",
                "异常343",
                "异常344",
                "异常345",
                "异常346",
                "异常347",
                "异常348",
                "异常349",
                "异常350",
                "异常351",
                "异常352",
                "异常353",
                "异常354",
                "异常355",
                "异常356",
                "异常357",
                "异常358",
                "异常359",
                "异常360",
                "异常361",
                "异常362",
                "异常363",
                "异常364",
                "异常365",
                "异常366",
                "异常367",
                "异常368",
                "异常369",
                "异常370",
                "异常371",
                "异常372",
                "异常373",
                "异常374",
                "异常375",
                "异常376",
                "异常377",
                "异常378",
                "异常379",
                "异常380",
                "异常381",
                "异常382",
                "异常383",
                "异常384",
                "异常385",
                "异常386",
                "异常387",
                "异常388",
                "异常389",
                "异常390",
                "异常391",
                "异常392",
                "异常393",
                "异常394",
                "异常395",
                "异常396",
                "异常397",
                "异常398",
                "异常399",
                "异常400",
                "异常401",
                "异常402",
                "异常403",
                "异常404",
                "异常405",
                "异常406",
                "异常407",
                "异常408",
                "异常409",
                "异常410",
                "异常411",
                "异常412",
                "异常413",
                "异常414",
                "异常415",
                "异常416",
                "异常417",
                "异常418",
                "异常419",
                "异常420",
                "异常421",
                "异常422",
                "异常423",
                "异常424",
                "异常425",
                "异常426",
                "异常427",
                "异常428",
                "异常429",
                "异常430",
                "异常431",
                "异常432",
                "异常433",
                "异常434",
                "异常435",
                "异常436",
                "异常437",
                "异常438",
                "异常439",
                "异常440",
                "异常441",
                "异常442",
                "异常443",
                "异常444",
                "异常445",
                "异常446",
                "异常447",
                "异常448",
                "异常449",
                "异常450",
                "异常451",
                "异常452",
                "异常453",
                "异常454",
                "异常455",
                "异常456",
                "异常457",
                "异常458",
                "异常459",
                "异常460",
                "异常461",
                "异常462",
                "异常463",
                "异常464",
                "异常465",
                "异常466",
                "异常467",
                "异常468",
                "异常469",
                "异常470",
                "异常471",
                "异常472",
                "异常473",
                "异常474",
                "异常475",
                "异常476",
                "异常477",
                "异常478",
                "异常479",
                "异常480",
                "异常481",
                "异常482",
                "异常483",
                "异常484",
                "异常485",
                "异常486",
                "异常487",
                "异常488",
                "异常489",
                "异常490",
                "异常491",
                "异常492",
                "异常493",
                "异常494",
                "异常495",
                "异常496",
                "异常497",
                "异常498",
                "异常499",
                "异常500",
                "异常501",
                "异常502",
                "异常503",
                "异常504",
                "异常505",
                "异常506",
                "异常507",
                "异常508",
                "异常509",
                "异常510",
                "异常511",
                "异常512",
                "异常513",
                "异常514",
                "异常515",
                "异常516",
                "异常517",
                "异常518",
                "异常519",
                "异常520",
                "异常521",
                "异常522",
                "异常523",
                "异常524",
                "异常525",
                "异常526",
                "异常527",
                "异常528",
                "异常529",
                "异常530",
                "异常531",
                "异常532",
                "异常533",
                "异常534",
                "异常535",
                "异常536",
                "异常537",
                "异常538",
                "异常539",
                "异常540",
                "异常541",
                "异常542",
                "异常543",
                "异常544",
                "异常545",
                "异常546",
                "异常547",
                "异常548",
                "异常549",
                "异常550",
                "异常551",
                "异常552",
                "异常553",
                "异常554",
                "异常555",
                "异常556",
                "异常557",
                "异常558",
                "异常559",
                "异常560",
                "异常561",
                "异常562",
                "异常563",
                "异常564",
                "异常565",
                "异常566",
                "异常567",
                "异常568",
                "异常569",
                "异常570",
                "异常571",
                "异常572",
                "异常573",
                "异常574",
                "异常575",
                "异常576",
                "异常577",
                "异常578",
                "异常579",
                "注液上下料机械手防撞检测到了",
                "异常581",
                "异常582",
                "异常583",
                "异常584",
                "异常585",
                "异常586",
                "异常587",
                "异常588",
                "异常589",
                "异常590",
                "异常591",
                "异常592",
                "异常593",
                "异常594",
                "异常595",
                "异常596",
                "异常597",
                "异常598",
                "轴1_Axis.Error",
                "轴2_Axis.Error",
                "轴3_Axis.Error",
                "轴4_Axis.Error",
                "轴5_Axis.Error",
                "轴6_Axis.Error",
                "轴7_Axis.Error",
                "轴8_Axis.Error",
                "轴9_Axis.Error",
                "轴10_Axis.Error",
                "轴11_Axis.Error",
                "轴12_Axis.Error",
                "轴13_Axis.Error",
                "轴14_Axis.Error",
                "轴15_Axis.Error",
                "轴16_Axis.Error",
                "轴17_Axis.Error",
                "轴18_Axis.Error",
                "轴19_Axis.Error",
                "轴20_Axis.Error",
                "轴21_Axis.Error",
                "轴22_Axis.Error",
                "轴23_Axis.Error",
                "轴24_Axis.Error",
                "轴25_Axis.Error",
                "轴26_Axis.Error",
                "轴27_Axis.Error",
                "轴28_Axis.Error",
                "轴29_Axis.Error",
                "轴30_Axis.Error",
                "轴31_Axis.Error",
                "轴32_Axis.Error",
                "轴33_Axis.Error",
                "轴34_Axis.Error",
                "轴35_Axis.Error",
                "轴36_Axis.Error",
                "轴37_Axis.Error",
                "轴38_Axis.Error",
                "轴39_Axis.Error",
                "轴40_Axis.Error",
                "轴41_Axis.Error",
                "轴42_Axis.Error",
                "轴43_Axis.Error",
                "轴44_Axis.Error",
                "轴45_Axis.Error",
                "轴46_Axis.Error",
                "轴47_Axis.Error",
                "轴48_Axis.Error",
                "轴49_Axis.Error",
                "轴50_Axis.Error",
                "轴51_Axis.Error",
                "轴52_Axis.Error",
                "轴53_Axis.Error",
                "轴54_Axis.Error",
                "轴55_Axis.Error",
                "轴56_Axis.Error",
                "轴57_Axis.Error",
                "轴58_Axis.Error",
                "轴59_Axis.Error",
                "轴60_Axis.Error",
                "轴61_Axis.Error",
                "轴62_Axis.Error",
                "轴63_Axis.Error",
                "轴64_Axis.Error",
                "轴65_Axis.Error",
                "轴66_Axis.Error",
                "轴67_Axis.Error",
                "轴68_Axis.Error",
                "轴69_Axis.Error",
                "轴70_Axis.Error",
                "轴71_Axis.Error",
                "轴72_Axis.Error",
                "轴73_Axis.Error",
                "轴74_Axis.Error",
                "轴75_Axis.Error",
                "轴76_Axis.Error",
                "轴77_Axis.Error",
                "轴78_Axis.Error",
                "轴79_Axis.Error",
                "轴80_Axis.Error",
                "轴81_Axis.Error",
                "轴82_Axis.Error",
                "轴83_Axis.Error",
                "轴84_Axis.Error",
                "轴85_Axis.Error",
                "轴86_Axis.Error",
                "轴87_Axis.Error",
                "轴88_Axis.Error",
                "轴89_Axis.Error",
                "轴90_Axis.Error",
                "轴91_Axis.Error",
                "轴92_Axis.Error",
                "轴93_Axis.Error",
                "轴94_Axis.Error",
                "轴95_Axis.Error",
                "轴96_Axis.Error",
                "轴97_Axis.Error",
                "轴98_Axis.Error",
                "轴99_Axis.Error",
                "轴100_Axis.Error",
                "异常701",
                "异常702",
                "异常703",
                "异常704",
                "轴1原点未确定",
                "轴2原点未确定",
                "轴3原点未确定",
                "轴4原点未确定",
                "轴5原点未确定",
                "轴6原点未确定",
                "轴7原点未确定",
                "轴8原点未确定",
                "轴9原点未确定",
                "轴10原点未确定",
                "轴11原点未确定",
                "轴12原点未确定",
                "轴13原点未确定",
                "轴14原点未确定",
                "轴15原点未确定",
                "轴16原点未确定",
                "轴17原点未确定",
                "轴18原点未确定",
                "轴19原点未确定",
                "轴20原点未确定",
                "轴21原点未确定",
                "轴22原点未确定",
                "轴23原点未确定",
                "轴24原点未确定",
                "轴25原点未确定",
                "轴26原点未确定",
                "轴27原点未确定",
                "轴28原点未确定",
                "轴29原点未确定",
                "轴30原点未确定",
                "轴31原点未确定",
                "轴32原点未确定",
                "轴33原点未确定",
                "轴34原点未确定",
                "轴35原点未确定",
                "轴36原点未确定",
                "轴37原点未确定",
                "轴38原点未确定",
                "轴39原点未确定",
                "轴40原点未确定",
                "轴41原点未确定",
                "轴42原点未确定",
                "轴43原点未确定",
                "轴44原点未确定",
                "轴45原点未确定",
                "轴46原点未确定",
                "轴47原点未确定",
                "轴48原点未确定",
                "轴49原点未确定",
                "轴50原点未确定",
                "轴51原点未确定",
                "轴52原点未确定",
                "轴53原点未确定",
                "轴54原点未确定",
                "轴55原点未确定",
                "轴56原点未确定",
                "轴57原点未确定",
                "轴58原点未确定",
                "轴59原点未确定",
                "轴60原点未确定",
                "轴61原点未确定",
                "轴62原点未确定",
                "轴63原点未确定",
                "轴64原点未确定",
                "轴65原点未确定",
                "轴66原点未确定",
                "轴67原点未确定",
                "轴68原点未确定",
                "轴69原点未确定",
                "轴70原点未确定",
                "轴71原点未确定",
                "轴72原点未确定",
                "轴73原点未确定",
                "轴74原点未确定",
                "轴75原点未确定",
                "轴76原点未确定",
                "轴77原点未确定",
                "轴78原点未确定",
                "轴79原点未确定",
                "轴80原点未确定",
                "轴81原点未确定",
                "轴82原点未确定",
                "轴83原点未确定",
                "轴84原点未确定",
                "轴85原点未确定",
                "轴86原点未确定",
                "轴87原点未确定",
                "轴88原点未确定",
                "轴89原点未确定",
                "轴90原点未确定",
                "轴91原点未确定",
                "轴92原点未确定",
                "轴93原点未确定",
                "轴94原点未确定",
                "轴95原点未确定",
                "轴96原点未确定",
                "轴97原点未确定",
                "轴98原点未确定",
                "轴99原点未确定",
                "轴100原点未确定",
                "异常805",
                "异常806",
                "异常807",
                "异常808",
                "轴1驱动报警",
                "轴2驱动报警",
                "轴3驱动报警",
                "轴4驱动报警",
                "轴5驱动报警",
                "轴6驱动报警",
                "轴7驱动报警",
                "轴8驱动报警",
                "轴9驱动报警",
                "轴10驱动报警",
                "轴11驱动报警",
                "轴12驱动报警",
                "轴13驱动报警",
                "轴14驱动报警",
                "轴15驱动报警",
                "轴16驱动报警",
                "轴17驱动报警",
                "轴18驱动报警",
                "轴19驱动报警",
                "轴20驱动报警",
                "轴21驱动报警",
                "轴22驱动报警",
                "轴23驱动报警",
                "轴24驱动报警",
                "轴25驱动报警",
                "轴26驱动报警",
                "轴27驱动报警",
                "轴28驱动报警",
                "轴29驱动报警",
                "轴30驱动报警",
                "轴31驱动报警",
                "轴32驱动报警",
                "轴33驱动报警",
                "轴34驱动报警",
                "轴35驱动报警",
                "轴36驱动报警",
                "轴37驱动报警",
                "轴38驱动报警",
                "轴39驱动报警",
                "轴40驱动报警",
                "轴41驱动报警",
                "轴42驱动报警",
                "轴43驱动报警",
                "轴44驱动报警",
                "轴45驱动报警",
                "轴46驱动报警",
                "轴47驱动报警",
                "轴48驱动报警",
                "轴49驱动报警",
                "轴50驱动报警",
                "轴51驱动报警",
                "轴52驱动报警",
                "轴53驱动报警",
                "轴54驱动报警",
                "轴55驱动报警",
                "轴56驱动报警",
                "轴57驱动报警",
                "轴58驱动报警",
                "轴59驱动报警",
                "轴60驱动报警",
                "轴61驱动报警",
                "轴62驱动报警",
                "轴63驱动报警",
                "轴64驱动报警",
                "轴65驱动报警",
                "轴66驱动报警",
                "轴67驱动报警",
                "轴68驱动报警",
                "轴69驱动报警",
                "轴70驱动报警",
                "轴71驱动报警",
                "轴72驱动报警",
                "轴73驱动报警",
                "轴74驱动报警",
                "轴75驱动报警",
                "轴76驱动报警",
                "轴77驱动报警",
                "轴78驱动报警",
                "轴79驱动报警",
                "轴80驱动报警",
                "轴81驱动报警",
                "轴82驱动报警",
                "轴83驱动报警",
                "轴84驱动报警",
                "轴85驱动报警",
                "轴86驱动报警",
                "轴87驱动报警",
                "轴88驱动报警",
                "轴89驱动报警",
                "轴90驱动报警",
                "轴91驱动报警",
                "轴92驱动报警",
                "轴93驱动报警",
                "轴94驱动报警",
                "轴95驱动报警",
                "轴96驱动报警",
                "轴97驱动报警",
                "轴98驱动报警",
                "轴99驱动报警",
                "轴100驱动报警",
                "异常909",
                "异常910",
                "异常911",
                "异常912",
                "A工位真空超时",
                "A工位大气超时",
                "A工位高压超时",
                "B工位真空超时",
                "B工位大气超时",
                "B工位高压超时",
                "C工位真空超时",
                "C工位大气超时",
                "C工位高压超时",
                "D工位真空超时",
                "D工位大气超时",
                "D工位高压超时",
                "E工位真空超时",
                "E工位大气超时",
                "E工位高压超时",
                "F工位真空超时",
                "F工位大气超时",
                "F工位高压超时",
                "G工位真空超时",
                "G工位大气超时",
                "G工位高压超时",
                "8#缸真空超时",
                "8#缸大气超时",
                "8#缸高压超时",
                "9#缸真空超时",
                "9#缸大气超时",
                "9#缸高压超时",
                "10#缸真空超时",
                "10#缸大气超时",
                "10#缸高压超时",
                "11#缸真空超时",
                "11#缸大气超时",
                "11#缸高压超时",
                "12#缸真空超时",
                "12#缸大气超时",
                "12#缸高压超时",
                "13#缸真空超时",
                "13#缸大气超时",
                "13#缸高压超时",
                "14#缸真空超时",
                "14#缸大气超时",
                "14#缸高压超时",
                "15#缸真空超时",
                "15#缸大气超时",
                "15#缸高压超时",
                "16#缸真空超时",
                "16#缸大气超时",
                "16#缸高压超时",
                "异常961",
                "异常962",
                "异常963",
                "异常964",
                "异常965",
                "异常966",
                "异常967",
                "异常968",
                "异常969",
                "异常970",
                "异常971",
                "异常972",
                "异常973",
                "异常974",
                "异常975",
                "异常976",
                "异常977",
                "异常978",
                "异常979",
                "异常980",
                "异常981",
                "异常982",
                "异常983",
                "异常984",
                "异常985",
                "异常986",
                "异常987",
                "异常988",
                "异常989",
                "异常990",
                "异常991",
                "异常992",
                "异常993",
                "异常994",
                "异常995",
                "异常996",
                "异常997",
                "异常998",
                "异常999",
                "异常1000",
                "设备运行中",
                "设备停止中",
                "设备异常中",
                "手动模式中",
                "暂停模式中",
                "自动模式中",
                "结束投入中。。。",
                "初始化未完成。。。",
                "设备正在初始化中。。。",
                "提示10",
                "提示11",
                "提示12",
                "提示13",
                "提示14",
                "提示15",
                "提示16",
                "扫码短路NG流拉满料了",
                "前称重NG流拉满料了",
                "后称重NG流拉满料了",
                "出料NG流拉满料了",
                "下层储液罐没有电解液了",
                "残液罐满了",
                "下层DMC罐没有DMC了",
                "擦洗DMC罐没有DMC了",
                "注液站没有在初始位",
                "胶钉缺料",
                "前称清零超时",
                "后称清零超时",
                "补液称重清零超时",
                "补液NG满料",
                "提示31",
                "提示32",
                "提示33",
                "提示34",
                "提示35",
                "提示36",
                "提示37",
                "提示38",
                "提示39",
                "提示40",
                "提示41",
                "提示42",
                "提示43",
                "提示44",
                "提示45",
                "提示46",
                "提示47",
                "提示48",
                "提示49",
                "提示50",
                "提示51",
                "提示52",
                "提示53",
                "提示54",
                "提示55",
                "提示56",
                "提示57",
                "提示58",
                "提示59",
                "提示60",
                "提示61",
                "提示62",
                "提示63",
                "提示64",
                "提示65",
                "提示66",
                "提示67",
                "提示68",
                "提示69",
                "提示70",
                "提示71",
                "提示72",
                "提示73",
                "提示74",
                "提示75",
                "提示76",
                "提示77",
                "提示78",
                "提示79",
                "提示80",
                "提示81",
                "提示82",
                "提示83",
                "提示84",
                "提示85",
                "提示86",
                "提示87",
                "提示88",
                "提示89",
                "提示90",
                "提示91",
                "提示92",
                "提示93",
                "提示94",
                "提示95",
                "提示96",
                "提示97",
                "提示98",
                "提示99",
                "提示100",
                "提示101",
                "提示102",
                "提示103",
                "提示104",
                "提示105",
                "提示106",
                "提示107",
                "提示108",
                "提示109",
                "提示110",
                "提示111",
                "提示112"
            };
        }

        private void Timer5_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (GlobalValues.MesOnOff)
                {
                    var datas = AFDB.GetMesTranInfo();
                    if (datas != null)
                    {
                        foreach (var data in datas)
                        {
                            var returnVal = Lib.TestDataGroupInfo(data.Message);
                            if (!returnVal.StartsWith("NotConnect"))
                            {
                                data.RetranCount++;
                                if (returnVal.ToUpper().Contains("TRUE"))
                                {
                                    Logger.Info(string.Format("{0} 称重数据重传MES成功", data.Barcode));
                                    var code = AFDB.UpdateMesRetranStatus(data.ID, true, data.RetranCount);
                                    if (code > 0)
                                    {
                                        Logger.Info(string.Format("更新{0}MES重传状态成功", data.Barcode));
                                    }
                                    else
                                    {
                                        Logger.Info(string.Format("更新{0}MES重传状态失败", data.Barcode));
                                    }
                                }
                                else
                                {
                                    Logger.Info(string.Format("{0} 称重数据重传MES失败 {1}", data.Barcode, returnVal));
                                    var code = AFDB.UpdateMesRetranStatus(data.ID, true, data.RetranCount);
                                    if (code > 0)
                                    {
                                        Logger.Info(string.Format("更新{0}MES重传状态成功", data.Barcode));
                                    }
                                    else
                                    {
                                        Logger.Info(string.Format("更新{0}MES重传状态失败", data.Barcode));
                                    }
                                }
                            }

                        }
                    }
                }

            }
            catch (Exception ex)
            {
                Logger.Info(string.Format("上传数据发生异常 {0}", ex.Message));
            }
        }

        object Exportlocker = new object();
        private void Timer4_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Locate.ToUpper() == "ZH")
            {
                if (Monitor.TryEnter(Exportlocker))
                {
                    try
                    {
                        string fullpath = "";
                        try
                        {
                            var time = DateTime.Now;
                            var weights = AFDB.GetAfterFirst2(time);
                            if (weights != null && weights.Count > 0)
                            {
                                var filename = string.Format("{0}_{1}.xls", MachineCode, time.ToString(("yyyyMMddHHmmss")));
                                fullpath = Path.Combine(ExportPath, filename);
                                if (!Directory.Exists(ExportPath))
                                {
                                    Directory.CreateDirectory(ExportPath);
                                }
                                var saveCode = ExcelHelper.SaveToExcel(fullpath, weights);
                                if (saveCode)
                                {
                                    Log(string.Format("{0} 导出保存成功", fullpath));

                                    AFDB.UpdateExportDataStatus2(time);
                                }
                                else
                                {
                                    Log(string.Format("{0} 导出保存失败", fullpath));
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Log(string.Format("导出文件{0}异常:{1}", fullpath, ex.Message));
                        }
                    }
                    catch (Exception ex)
                    {
                        Log(string.Format("导出文件异常:{0}", ex));
                    }
                    finally
                    {
                        Monitor.Exit(Exportlocker);
                    }
                }
            }
            else
            {
                if (Monitor.TryEnter(Exportlocker))
                {
                    try
                    {
                        var dates = AFDB.GetUnExportDates();
                        if (dates != null && dates.Count > 0)
                        {
                            foreach (var date in dates)
                            {
                                try
                                {
                                    var weights = AFDB.GetAfterFirst(date.Date);
                                    if (weights != null && weights.Count > 0)
                                    {
                                        var sb = new StringBuilder();
                                        sb.AppendFormat("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13}\n",
                                            "条码", "称号", "站号", "列号", "行号", "前重", "后重", "注液量", "偏差值", "前重结果", "后重结果", "结果", "补液量", "补液后称重", "生产日期");
                                        foreach (var w in weights)
                                        {
                                            sb.AppendFormat("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}\n",
                                               w.Code, w.Index, w.TrayNum, w.TrayIndex, w.TrayCol, w.BeforWeight_One, w.AfterWeight_One, w.InjectionNum_One,
                                               w.InjectionNum_Offset_One, w.BeforeResult_One, w.AfterResult_One, w.Result_One, w.SupplementNum_One, w.SupplementWeight_One, w.ProductDate);
                                        }

                                        DateTime saveDate;
                                        DateTime.TryParse(date.Date, out saveDate);
                                        var basePath = Path.Combine(ExportPath, saveDate.Year.ToString(), saveDate.Month.ToString());
                                        if (!Directory.Exists(basePath))
                                        {
                                            Directory.CreateDirectory(basePath);
                                        }
                                        var fileName = Path.Combine(basePath, date.Date + ".CSV");
                                        var fullName = Path.GetFullPath(fileName);
                                        File.WriteAllText(fullName, sb.ToString(), Encoding.UTF8);
                                        Log(string.Format("{0} 导出保存成功", fullName));
                                        AFDB.UpdateExportDataStatus(date.Date);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Log(string.Format("导出文件{0}.CSV异常:{1}", date.Date, ex));
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log(string.Format("导出文件异常:{0}", ex));
                    }
                    finally
                    {
                        Monitor.Exit(Exportlocker);
                    }
                }
            }
        }

        private void Timer2_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                DatabaseStatus = CNTDB.GetDatabaseStatus();
            }
            catch (Exception ex)
            { }
        }

        #region new

        System.Timers.Timer KeepAlive = new System.Timers.Timer(2000);

        bool isConnected;
        public bool IsConnected
        {
            get { return isConnected; }
            set
            {
                if (isConnected != value)
                {
                    isConnected = value;
                    Messenger.Default.Send<bool>(value, "SendPLCStatus");
                    Logger.Info(string.Format("连接{0}", value ? "成功" : "失败"));
                }
            }
        }

        public bool IsConnected2 { get; set; }
        bool databaseStatus;
        public bool DatabaseStatus
        {
            get { return databaseStatus; }
            set
            {
                if (databaseStatus != value)
                {
                    databaseStatus = value;
                    Messenger.Default.Send<bool>(databaseStatus, "SendDatabaseStatus");
                    Logger.Info(string.Format("数据库连接{0}", value ? "成功" : "失败"));
                }
            }
        }

        object locker1 = new object();
        Task createTask;
        Task runTask;
        Task run1;
        Task run2;

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (run1 == null || run1.IsCompleted)
            {
                run1 = CreateRun1();
            }

            if (run2 == null || run2.IsCompleted)
            {
                Thread.Sleep(1000);
                run2 = CreateRun2();
            }
        }

        public bool Open(Plc plc)
        {
            try
            {
                plc.Open();
                Logger.Info(string.Format("{0}连接成功", plc.IP));
                return true;

            }
            catch (Exception ex)
            {
                Logger.Info(string.Format("{0}连接失败 {1}", plc.IP, ex.Message));
                return false;
            }
        }

        bool Task1Run = true;
        public Task CreateRun1()
        {
            return Task.Run(() =>
            {
                while (Task1Run)
                {
                    try
                    {
                        //if (plc.IsConnected)
                        if (IsConnected)
                        {
                            //IsConnected = true;
                            short[] cmds1 = new short[7];
                            var t = new T();
                            lock (locker)
                            {
                                cmds1 = plc.Read(DataType.DataBlock, DBNo, 0, VarType.Int, 7) as short[];
                                plc.Write(DataType.DataBlock, DBNo, 88, r1);
                            }
                            if (cmds1 != null && cmds1.Length >= 7)
                            {
                                ReadCode = cmds1[0];
                                BeforWeight = cmds1[1];
                                AfterWeight = cmds1[2];
                                Supplement = cmds1[3];
                                ShortCicuteTest = cmds1[4];
                                BeforeWeightClear = cmds1[5];
                                AfterWeightClear = cmds1[6];
                            }
                        }
                        else
                        {
                            Logger.Info(string.Format("{0}通信失败1", plc.IP));
                            IsConnected = Open(plc);
                        }
                        Thread.Sleep(100);
                    }
                    catch (Exception ex)
                    {
                        IsConnected = false;
                        Logger.Info(string.Format("{0}通信失败2 {1}", plc.IP, ex), false);
                    }
                }
            });
        }

        bool Task2Run = true;

        bool runing = false;
        BitArray Alarms;
        BitArray bits = null;
        public Task CreateRun2()
        {
            return Task.Run(() =>
            {
                while (Task1Run)
                {
                    try
                    {
                        if (IsConnected2)
                        {
                            lock (locker2)
                            {
                                bits = plc2.Read(DataType.DataBlock, DBNo1, 0, VarType.Bit, 1113) as BitArray;
                            }
                            EquRunning = bits[1000];
                            EquPause = bits[1001] & !bits[1000] & !bits[1002];
                            EquAlarm = bits[1002];
                        }
                        else
                        {
                            IsConnected2 = Open(plc2);
                            Logger.Info(string.Format("{0} {1} 通信失败3", plc2.IP, IsConnected2));
                        }
                        Thread.Sleep(1000);
                    }
                    catch (Exception ex)
                    {
                        IsConnected2 = false;
                        Logger.Info(string.Format("{0}通信失败4 {1}", plc2.IP, ex), false);
                    }
                }
            });
        }

        bool equRunning = false;
        /// <summary>
        /// 设备状态 运行
        /// </summary>
        public bool EquRunning
        {
            get { return equRunning; }
            set
            {
                if (equRunning != value)
                {
                    equRunning = value;
                    if (equRunning)
                    {
                        Logger.Info(string.Format("设备状态发生变化:{0} 运行中", GlobalValues.EquNo));
                        if (GlobalValues.MesOnOff)
                        {
                            Task.Run(() =>
                            {
                                try
                                {
                                    var returnVal = Lib.DeviecStatusInfo(GlobalValues.EquNo, "Run",
                                            DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "", GlobalValues.EmpNo);
                                    if (returnVal.ToUpper().Contains("TRUE"))
                                    {
                                        Logger.Info("Run状态上传成功", false);
                                    }
                                    else
                                    {
                                        Logger.Info(string.Format("Run状态上传失败 {0}", returnVal));
                                    }
                                }
                                catch { }
                            });
                        }
                    }
                }
            }
        }
        bool equPause = false;
        /// <summary>
        /// 设备状态 暂停
        /// </summary>
        public bool EquPause
        {
            get { return equPause; }
            set
            {
                if (equPause != value)
                {
                    equPause = value;
                    if (equPause)
                    {
                        Logger.Info(string.Format("设备状态发生变化:{0} 暂停中", GlobalValues.EquNo));
                        if (GlobalValues.MesOnOff)
                        {
                            Task.Run(() =>
                            {
                                try
                                {
                                    var returnVal = Lib.DeviecStatusInfo(GlobalValues.EquNo, "Down",
                                          DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "", GlobalValues.EmpNo);
                                    if (returnVal.ToUpper().Contains("TRUE"))
                                    {
                                        Logger.Info("暂停状态上传成功", false);
                                    }
                                    else
                                    {
                                        Logger.Info(string.Format("暂停状态上传失败 {0}", returnVal));
                                    }
                                }
                                catch { }
                            });
                        }
                    }
                }
            }
        }
        bool equAlarm = false;
        /// <summary>
        /// 设备状态 报警
        /// </summary>
        public bool EquAlarm
        {
            get { return equAlarm; }
            set
            {
                if (equAlarm != value)
                {
                    equAlarm = value;
                    if (equAlarm)
                    {
                        Logger.Info(string.Format("设备状态发生变化:{0} 报警中", GlobalValues.EquNo));
                        if (GlobalValues.MesOnOff)
                        {
                            Task.Run(() =>
                            {
                                try
                                {
                                    if (bits != null && bits.Length > 0)
                                    {
                                        var errMsg = new List<string>();
                                        for (var i = 0; i < bits.Length; i++)
                                        {
                                            if (i >= 1000 && i <= 1008)
                                            {
                                                continue;
                                            }
                                            if (bits[i])
                                            {
                                                errMsg.Add(string.Format("{0}:{1}", i.ToString("00000"), ErrorMsg[i]));
                                            }
                                        }
                                        var err = string.Format("|{0}|", string.Join("|", errMsg));
                                        var returnVal = Lib.DeviecStatusInfo(GlobalValues.EquNo, "Warn",
                                           DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), err, GlobalValues.EmpNo);
                                        if (returnVal.ToUpper().Contains("TRUE"))
                                        {
                                            Logger.Info("报警状态上传成功", false);
                                        }
                                        else
                                        {
                                            Logger.Info(string.Format("报警状态上传失败 {0}", returnVal));
                                        }
                                    }

                                }
                                catch { }
                            });
                        }
                    }
                }
            }
        }
        bool equWait = false;
        /// <summary>
        /// 设备状态 待机
        /// </summary>
        public bool EquWait
        {
            get { return equWait; }
            set
            {
                if (equWait != value)
                {
                    equWait = value;
                    if (equWait)
                    {
                        Logger.Info(string.Format("设备状态发生变化:{0} 待机中", GlobalValues.EquNo));
                    }
                }
            }
        }
        //bool equClosed = false;
        ///// <summary>
        ///// 设备状态 关机
        ///// </summary>
        //public bool EquClosed
        //{
        //    get { return equClosed; }
        //    set
        //    {
        //        if (equClosed != value)
        //        {
        //            equClosed = value;
        //            if (equClosed)
        //            {
        //                SDB.AddMachineStatus(GlobalValues.EquNo, 0);
        //                Logger.Info(string.Format("设备状态发生变化:{0} 关机中", GlobalValues.EquNo));
        //            }
        //        }
        //    }
        //}

        List<string> ErrorMsg;


        #endregion


        int readCodeLock = 0;
        public int ReadCode
        {
            set
            {
                if (value == 1)
                {
                    if (0 == Interlocked.Exchange(ref readCodeLock, 1))
                    {
                        Task.Factory.StartNew((S) =>
                        {
                            Logger.Info(string.Format("开始前扫码"));
                            ReadCodeHandle();
                            Logger.Info(string.Format("前扫码完成"));
                        }, "", TaskCreationOptions.LongRunning).ContinueWith(t => Interlocked.Exchange(ref readCodeLock, 0));
                    }
                }
            }
        }
        int readCodeLock2 = 0;
        public int ReadCode2
        {
            set
            {
                if (value == 1)
                {
                    if (0 == Interlocked.Exchange(ref readCodeLock2, 1))
                    {
                        Task.Factory.StartNew((S) =>
                        {
                            Logger.Info(string.Format("开始后扫码"));
                            ReadCodeHandle2();
                            Logger.Info(string.Format("后扫码完成"));

                        }, "", TaskCreationOptions.LongRunning).ContinueWith(t => Interlocked.Exchange(ref readCodeLock2, 0));
                    }
                }
            }
        }
        int beforWeightLock = 0;
        public int BeforWeight
        {
            set
            {
                if (value == 1)
                {
                    if (0 == Interlocked.Exchange(ref beforWeightLock, 1))
                    {
                        Task.Factory.StartNew((S) =>
                        {
                            Logger.Info(string.Format("开始前称重"));
                            BeforWeightHandle();
                            Logger.Info(string.Format("前称重完成"));
                        }, "", TaskCreationOptions.LongRunning).ContinueWith(t => Interlocked.Exchange(ref beforWeightLock, 0));
                    }
                }
            }
        }
        int afterWeighLock = 0;
        public int AfterWeight
        {
            set
            {
                if (value == 1)
                {
                    if (0 == Interlocked.Exchange(ref afterWeighLock, 1))
                    {
                        Task.Factory.StartNew((S) =>
                        {
                            Logger.Info(string.Format("开始后称重"));
                            AfterWeightHandle();
                            Logger.Info(string.Format("后称重完成"));
                        }, "", TaskCreationOptions.LongRunning).ContinueWith(t => Interlocked.Exchange(ref afterWeighLock, 0));
                    }
                }
            }
        }
        int supplementLock = 0;
        public int Supplement
        {
            set
            {
                if (value == 1)
                {
                    if (0 == Interlocked.Exchange(ref supplementLock, 1))
                    {
                        Task.Factory.StartNew((S) =>
                        {

                        }, "", TaskCreationOptions.LongRunning).ContinueWith(t => Interlocked.Exchange(ref supplementLock, 0));
                    }
                }
            }
        }

        int beforeWeightClearLock = 0;
        public int BeforeWeightClear
        {
            set
            {
                if (value == 1)
                {
                    if (0 == Interlocked.Exchange(ref beforeWeightClearLock, 1))
                    {
                        Task.Factory.StartNew((S) =>
                        {
                            Logger.Info(string.Format("开始前称清零"));
                            BeforeWeightClearHandle();
                            Logger.Info(string.Format("前称清零完成"));

                        }, "", TaskCreationOptions.LongRunning).ContinueWith(t => Interlocked.Exchange(ref beforeWeightClearLock, 0));
                    }
                }
            }
        }
        int afterWeightClearLock = 0;
        public int AfterWeightClear
        {
            set
            {
                if (value == 1)
                {
                    if (0 == Interlocked.Exchange(ref afterWeightClearLock, 1))
                    {
                        Task.Factory.StartNew((S) =>
                        {
                            Logger.Info(string.Format("开始后称清零"));
                            AfterWeightClearHandle();
                            Logger.Info(string.Format("后称清零完成"));
                        }, "", TaskCreationOptions.LongRunning).ContinueWith(t => Interlocked.Exchange(ref afterWeightClearLock, 0));
                    }
                }
            }
        }
        //public UInt16 Row { get; set; }
        //public UInt16 Col { get; set; }
        //public UInt16 Station { get; set; }
        //public UInt16 Loop { get; set; }
        //public float Vacuum { get; set; }
        //public float PPressure { get; set; }
        //public float NPressure { get; set; }
        //public float OnceWeight { get; set; }


        int shortCicuteTestLock = 0;
        public int ShortCicuteTest
        {
            set
            {
                if (value == 1)
                {
                    if (0 == Interlocked.Exchange(ref shortCicuteTestLock, 1))
                    {
                        Task.Factory.StartNew((S) =>
                        {
                            Logger.Info(string.Format("开始短路测试"));
                            if (GlobalValues.TestType == 1)
                            {
                                ShortCicuteTestHandle();
                            }
                            else
                            {
                                NewShortCicuteTestHandle();
                            }
                            Logger.Info(string.Format("短路测试完成"));
                        }, "", TaskCreationOptions.LongRunning).ContinueWith(t => Interlocked.Exchange(ref shortCicuteTestLock, 0));
                    }
                }
            }
        }

        int readCodeBase = 84;
        int classLen = 52;
        short[] mesResultAddr = new short[] { 94, 146 };
        short[] ycWeightAddr = new short[] { 94, 146 };
        short mesCheckFinish = 2676;
        public void ReadCodeHandle()
        {
            short resultVal = 0;
            try
            {
                lock (locker)
                {
                    plc.Write(DataType.DataBlock, DBNo, 0, r0);
                }
                Interlocked.Increment(ref InCount);
                var count = 0;
                FrontScanner.StartScan();
                var scanResult = FrontScanner.Receive().Trim();
                long snowflake = _snowflake.NextId();//雪花ID
                if (!Regex.IsMatch(scanResult, StrRegex))
                {
                    resultVal = r2;
                    Logger.Error(string.Format("前扫码失败或不符条码编码规则 {0}", scanResult));
                    return;
                }
                if (GlobalValues.MesOnOff)
                {
                    var testResult = Lib.GroupTest(scanResult, GlobalValues.EquNo, GlobalValues.EmpNo, GlobalValues.MoNumber, GlobalValues.GroupName);
                    //Logger.Info(string.Format("工序校验，条码:{0},设备编号:{1},员工编号:{2}.结果：{3}", scanResult, GlobalValues.EquNo, GlobalValues.EmpNo, testResult));
                    Logger.Info($"工序校验，条码:{scanResult},设备编号:{GlobalValues.EquNo},员工编号:{GlobalValues.EmpNo},制令单号:{GlobalValues.MoNumber},组别:{GlobalValues.GroupName}.结果：{testResult}");
                    if (testResult.Contains("TRUE"))
                    {
                        Logger.Info(string.Format("工序校验成功，条码:{0},设备编号:{1},员工编号:{2}.结果：{3}", scanResult, GlobalValues.EquNo, GlobalValues.EmpNo, testResult));
                        resultVal = r1;
                    }
                    else
                    {
                        Logger.Info(string.Format("工序校验失败，条码:{0},设备编号:{1},员工编号:{2}.结果：{3}", scanResult, GlobalValues.EquNo, GlobalValues.EmpNo, testResult));
                        resultVal = r2;
                        return;
                    }
                    if (GlobalValues.MesGroupCheckOnOff)
                    {
                        var checkResult1 = MESCheck.GroupNameCheck(scanResult, GlobalValues.GroupName, GlobalValues.MoNumber, GlobalValues.GroupCode, GlobalValues.EmpNo);
                        Logger.Info(string.Format("组别校验，条码:{0},组别:{1},制令单:{2},工序代码:{3},员工编号:{4}.结果：{5}", scanResult, GlobalValues.GroupName, GlobalValues.MoNumber, GlobalValues.GroupCode, GlobalValues.EmpNo, checkResult1));
                        if (checkResult1.Contains("TRUE"))
                        {
                            Logger.Info(string.Format("组别校验成功，条码:{0},组别:{1},制令单:{2},工序代码:{3},员工编号:{4}.结果：{5}", scanResult, GlobalValues.GroupName, GlobalValues.MoNumber, GlobalValues.GroupCode, GlobalValues.EmpNo, checkResult1));
                            resultVal = r1;
                        }
                        else
                        {
                            Logger.Info(string.Format("组别校验失败，条码:{0},组别:{1},制令单:{2},工序代码:{3},员工编号:{4}.结果：{5}", scanResult, GlobalValues.GroupName, GlobalValues.MoNumber, GlobalValues.GroupCode, GlobalValues.EmpNo, checkResult1));
                            resultVal = r2;
                            return;
                        }
                    }

                    var mocheckresult = MESCheck.CheckProductMoNumber(scanResult, GlobalValues.MoNumber);
                    Logger.Info(string.Format("制令单校验，条码:{0},制令单:{1},结果:{2}", scanResult, GlobalValues.MoNumber, mocheckresult));
                    if (mocheckresult.Contains("TRUE"))
                    {
                        Logger.Info(string.Format("制令单校验成功，条码:{0},制令单:{1},结果:{2}", scanResult, GlobalValues.MoNumber, mocheckresult));
                        resultVal = r1;
                    }
                    else
                    {
                        Logger.Info(string.Format("制令单校验失败，条码:{0},制令单:{1},结果:{2}", scanResult, GlobalValues.MoNumber, mocheckresult));
                        resultVal = r2;
                        return;
                    }

                    var ItemBatchNo = "|" + GlobalValues.ItemNo + ":" + GlobalValues.ItemBatchNo + ";" + GlobalValues.ItemNum;
                    if (GlobalValues.ItemNo == "/")
                    {
                        Logger.Info(string.Format("物料校验，物料号为:/，不进行校验"));
                        resultVal = r1;
                    }
                    else
                    {
                        var checkResult2 = MESCheck.CellBOMItemsCheck(scanResult, GlobalValues.MoNumber, GlobalValues.EmpNo, GlobalValues.EquNo, ItemBatchNo);
                        Logger.Info(string.Format("物料校验，条码:{0},制令单:{1},设备编号:{2},员工编号:{3},物料信息:{4}.结果：{5}", scanResult, GlobalValues.MoNumber, GlobalValues.EquNo, GlobalValues.EmpNo, ItemBatchNo, checkResult2));
                        if (checkResult2.Contains("TRUE"))
                        {
                            Logger.Info(string.Format("物料校验成功，条码:{0},制令单:{1},设备编号:{2},员工编号:{3},物料信息:{4}.结果：{5}", scanResult, GlobalValues.MoNumber, GlobalValues.EquNo, GlobalValues.EmpNo, ItemBatchNo, checkResult2));
                            resultVal = r1;
                        }
                        else
                        {
                            Logger.Info(string.Format("物料校验失败，条码:{0},制令单:{1},设备编号:{2},员工编号:{3},物料信息:{4}.结果：{5}", scanResult, GlobalValues.MoNumber, GlobalValues.EquNo, GlobalValues.EmpNo, ItemBatchNo, checkResult2));
                            resultVal = r2;
                            return;
                        }
                    }
                    //CellBOMItemsCheck
                }
                //var s1 = new byte[] { 0x30 };
                //var s2 = new byte[] { (byte)scanResult.Length };
                //var s3 = Encoding.Default.GetBytes(scanResult.Trim());
                //var s4 = s1.Concat(s2).Concat(s3).ToArray();
                //lock (locker)
                //{
                //    plc.Write(DataType.DataBlock, DBNo, 94, s4);
                //}
                //Logger.Info(string.Format("传条码给PLC {0}", scanResult));

                var s1 = new byte[] { 0x30 };
                var s2 = new byte[] { (byte)snowflake.ToString().Length };
                var s3 = Encoding.Default.GetBytes(snowflake.ToString().Trim());
                var s4 = s1.Concat(s2).Concat(s3).ToArray();
                lock (locker)
                {
                    plc.Write(DataType.DataBlock, DBNo, 94, s4);
                }
                Logger.Info(string.Format("传条码给PLC {0},ID:{1}", scanResult, snowflake));

                double? oneInjBeforWeight = 0;
                double? oneInjAfterWeight = 0;

                double? oneInjBeforWeight1 = 0;
                double? oneInjAfterWeight1 = 0;

                double? twoInjBeforWeight = 0;//返工
                double? twoInjAfterWeight = 0;//返工

                double? weightRework = 0;//补液后称重

                if (!GlobalValues.Rework)
                {
                    if (GlobalValues.MesOnOff)
                    {
                        var retVal = string.Empty;
                        if (GlobalValues.OpType.ToUpper() == "SC")
                        {
                            retVal = Lib.GetWeightBeforeInjectionC(scanResult);
                            Logger.Info(string.Format("获取二次次注液数据{0}", retVal));
                        }
                        else
                        {
                            retVal = Lib.GetWeightBeforeInjectionC(scanResult);
                            Logger.Info(string.Format("获取一次注液数据{0}", retVal));
                        }

                        var data = JsonConvert.DeserializeObject<OneWeightResult>(retVal);
                        if (data != null)
                        {
                            if (data.Status.ToUpper() == "TRUE")
                            {
                                var item1 = data.TestResultDetail.Where(s => s.ItemCode == "WeightBefore").FirstOrDefault();
                                var item2 = data.TestResultDetail.Where(s => s.ItemCode == "WeightAfter").FirstOrDefault();

                                var item3 = data.TestResultDetail.Where(s => s.ItemCode == "WeightBeforeTwo").FirstOrDefault();//二次注液前重量
                                var item4 = data.TestResultDetail.Where(s => s.ItemCode == "WeightAfterTwo").FirstOrDefault();//二次注液后重量

                                var item5 = data.TestResultDetail.Where(s => s.ItemCode == "WeightRework").FirstOrDefault();//一注补液后重量
                                var item6 = data.TestResultDetail.Where(s => s.ItemCode == "WeightReworkTwo").FirstOrDefault();//二注补液后重量

                                oneInjBeforWeight = item1 == null ? 0 : item1.Result;
                                oneInjAfterWeight = item2 == null ? 0 : item2.Result;

                                oneInjBeforWeight1 = item3 == null ? 0 : item3.Result;
                                oneInjAfterWeight1 = item4 == null ? 0 : item4.Result;

                                if (GlobalValues.OpType.ToUpper() == "YC")
                                {
                                    weightRework = item5 == null ? 0 : item5.Result;
                                }
                                else
                                {
                                    weightRework = item6 == null ? 0 : item6.Result;
                                }
                                Logger.Info(string.Format("一次前重 {0} 后重 {1},二次前重{2} 后重{3} 结果：{4}", oneInjBeforWeight, oneInjAfterWeight, oneInjBeforWeight1, oneInjAfterWeight1, scanResult));
                            }
                            else
                            {
                                Logger.Info(string.Format("获取一次注液数据失败{0} {1}", scanResult, data.TestResult));
                            }
                        }
                        else
                        {
                            Logger.Info(string.Format("获取一次注液数据解析异常{0} {1}", scanResult, retVal));
                        }
                    }
                    else
                    {
                        try
                        {
                            AfterWeightFirst beforWeightData_First= AFDB.GetOnceAfterWeightByBarcode(scanResult);
                            AfterWeightFirst beforWeightData  = AFDB.GetAfterWeight_Second(scanResult);
                            if (GlobalValues.OpType.ToUpper() == "SC"&& beforWeightData_First != null && beforWeightData != null)
                            {
                                

                                oneInjBeforWeight = beforWeightData_First.BeforWeight_One == null ? 0 : beforWeightData_First.BeforWeight_One;
                                oneInjAfterWeight = beforWeightData_First.AfterWeight_One == null ? 0 : beforWeightData_First.AfterWeight_One;

                                oneInjBeforWeight1 = beforWeightData.BeforWeight_One == null ? 0 : beforWeightData.BeforWeight_One;
                                oneInjAfterWeight1 = beforWeightData.AfterWeight_One == null ? 0 : beforWeightData.AfterWeight_One;

                                weightRework = beforWeightData.SupplementWeight_One == null ? 0 : beforWeightData.SupplementWeight_One;
                                Logger.Info(string.Format("离线模式取：一次前重 {0} 后重 {1},二次前重{2} 后重{3} 结果：{4}", oneInjBeforWeight, oneInjAfterWeight, oneInjBeforWeight1, oneInjAfterWeight1, scanResult));
                            }
                            else if (GlobalValues.OpType.ToUpper() == "EC" && beforWeightData_First != null)
                            {
                                oneInjBeforWeight = beforWeightData_First.BeforWeight_One == null ? 0 : beforWeightData_First.BeforWeight_One;
                                oneInjAfterWeight = beforWeightData_First.AfterWeight_One == null ? 0 : beforWeightData_First.AfterWeight_One;

                                oneInjBeforWeight1 = 0;
                                oneInjAfterWeight1 =0;

                                weightRework = beforWeightData_First.SupplementWeight_One == null ? 0 : beforWeightData.SupplementWeight_One;
                                Logger.Info(string.Format("离线模式取：一次前重 {0} 后重 {1},二次前重{2} 后重{3} 结果：{4}", oneInjBeforWeight, oneInjAfterWeight, oneInjBeforWeight1, oneInjAfterWeight1, scanResult));
                            }
                            else
                            {
                                Logger.Info($"{scanResult}离线模式取数据失败！！！");
                            }
                        }catch(Exception ex)
                        {
                            Logger.Info($"离线模式取数据错误：{ex.ToString()}");
                        }
                       
                    }

                    if (GlobalValues.EnableVarInj)
                    {
                        if (oneInjBeforWeight <= 0)
                        {
                            resultVal = r2;
                            Logger.Info(string.Format("一注前称重数据查找失败{0}", scanResult));
                            return;
                        }
                    }
                    var weight = new CodeFirst
                    {
                        ID = Guid.NewGuid(),
                        Code = scanResult,
                        ProductDate = DateTime.Now,
                        OnceBeforWeight = oneInjBeforWeight,
                        OnceAfterWeight = oneInjAfterWeight,
                        TwoBeforWeight = oneInjBeforWeight1,
                        TwoAfterWeight = oneInjAfterWeight1,
                        WeightRework = weightRework,
                        IsValidate = true,
                        Snowflake = snowflake
                    };
                    var result = CFDB.Add2(weight);
                    if (result > 0)
                    {
                        resultVal = r1;
                        count++;
                        Messenger.Default.Send<CodeFirst>(weight, "SendCodeFirst");
                        Logger.Info(string.Format("前扫码保存成功:{0}", weight.Code));
                    }
                    else
                    {
                        Logger.Info(string.Format("前扫码保存失败:{0}", weight.Code));
                    }
                    Logger.Info(string.Format("前扫码 共{0}条记录保存", count));

                    CNTDB.UpdateFrontCounter(InCount);
                    Messenger.Default.Send<int>(InCount, "SendINCount");
                }
                else
                {
                    var batt = AFDB.GetAfterWeightByBarcode(scanResult);
                    if (batt == null)
                    {
                        Logger.Info($"【返工】查询本地数据失败{scanResult}");
                        resultVal = r2;
                        return;
                    }
                    var sss = JsonConvert.SerializeObject(batt);
                    Logger.Info($"【返工】{GlobalValues.OpType.ToLower()} {sss}");
                    if (GlobalValues.OpType.ToUpper() == "EC")
                    {
                        var retVal = Lib.GetWeightBeforeInjectionC(scanResult);
                        Logger.Info(string.Format("从MES获取一注数据{0}", retVal));
                        var data = JsonConvert.DeserializeObject<OneWeightResult>(retVal);
                        if (data == null || data.Status.ToUpper() != "TRUE")
                        {
                            resultVal = r2;
                            Logger.Info(string.Format("从MES获取一注数据失败{0}", retVal));
                            return;
                        }
                        var item1 = data.TestResultDetail.Where(s => s.ItemCode == "WeightBefore").FirstOrDefault();
                        var item2 = data.TestResultDetail.Where(s => s.ItemCode == "WeightAfter").FirstOrDefault();
                        oneInjBeforWeight = item1 == null ? 0 : item1.Result;
                        oneInjAfterWeight = item2 == null ? 0 : item2.Result;
                        twoInjBeforWeight = batt.BeforWeight_One;
                        twoInjAfterWeight = batt.AfterWeight_One;
                    }
                    else
                    {
                        oneInjBeforWeight = batt.BeforWeight_One;
                        oneInjAfterWeight = batt.AfterWeight_One;
                    }
                    Logger.Info($"获取返工前数据{oneInjBeforWeight},{oneInjAfterWeight},{twoInjBeforWeight},{twoInjAfterWeight}");
                    var rework = new ReWork()
                    {
                        ID = Guid.NewGuid(),
                        Barcode = scanResult,
                        OneBeforWeight = (double)oneInjBeforWeight,
                        OneAfterWeight = (double)oneInjAfterWeight,
                        TwoBeforeWeight = (double)twoInjBeforWeight,
                        TwoAfterWeight = (double)twoInjAfterWeight,
                        LossVal = (double)(batt.LossVal ?? 0),
                        ProductDate = DateTime.Now
                    };
                    var code = CFDB.AddReWork(rework);
                    if (code > 0)
                    {
                        Logger.Info($"【返工扫码】{scanResult} 保存成功");
                        resultVal = r1;
                        var weight = new CodeFirst
                        {
                            ID = Guid.NewGuid(),
                            Code = scanResult,
                            ProductDate = DateTime.Now,
                            OnceBeforWeight = rework.OneBeforWeight,
                            OnceAfterWeight = rework.OneAfterWeight,
                            IsValidate = true
                        };
                        Messenger.Default.Send<CodeFirst>(weight, "SendCodeFirst");
                    }
                    else
                    {
                        Logger.Info($"【返工扫码】{scanResult} 保存失败");
                        resultVal = r2;
                    }
                }
            }
            catch (Exception ex)
            {
                resultVal = r2;
                Logger.Info(string.Format("{0} {1}", "ReadCodeHandle", ex));
            }
            finally
            {
                try
                {
                    lock (locker)
                    {
                        plc.Write(DataType.DataBlock, DBNo, 0, r0);
                        plc.Write(DataType.DataBlock, DBNo, 70, resultVal);
                        plc.Write(DataType.DataBlock, DBNo, 68, r1);
                    }
                }
                catch { }
                Logger.Info(string.Format("前扫码完成 扫码结果 {0}", resultVal));
            }
        }
        public void ReadCodeHandle2()
        {
            try
            {
                FrontScanner2.StartScan();
                var scanResult = FrontScanner2.Receive().Trim();
            }
            catch (Exception ex)
            {
                Logger.Info(string.Format("{0} {1}", "ReadCodeHandle2", ex.Message));
            }
            finally
            {
                try
                {
                    lock (locker)
                    {
                        plc.Write(DataType.DataBlock, DBNo, 8, 0);
                    }
                }
                catch { }
                // Logger.Info("后扫码扫码完成");
            }

            #region

            #endregion

        }

        int readBeforWeightBase = 154;
        int beforeClassLen = 38;
        /// <summary>
        /// 前称重
        /// </summary>
        public void BeforWeightHandle()
        {
            try
            {
                lock (locker)
                {
                    plc.Write(DataType.DataBlock, DBNo, 2, r0);
                }
                if (IsConnected)
                {
                    if (GlobalValues.Rework)
                    {
                        lock (locker)
                        {
                            plc.Write(DataType.DataBlock, DBNo, 2, r0);
                            plc.Write(DataType.DataBlock, DBNo, 44, (float)0);
                            plc.Write(DataType.DataBlock, DBNo, 82, r1);//OK
                        }
                        return;
                    }
                    var barcode = "";
                    var snowflake = "";
                    lock (locker)
                    {
                        //var barcodeByte = plc.ReadBytes(DataType.DataBlock, DBNo, readBeforWeightBase, 30);
                        //barcode = Kinlo.Model.Helper.ConvertByteToString(barcodeByte);

                        var snowflakeByte = plc.ReadBytes(DataType.DataBlock, DBNo, readBeforWeightBase, 30);
                        snowflake = Kinlo.Model.Helper.ConvertByteToString(snowflakeByte);
                        var battsnowflake = CFDB.GetCodeFirstBySnowflake(snowflake);
                        barcode = battsnowflake.Code;
                    }
                    if (!string.IsNullOrEmpty(barcode))
                    {
                        BeforeWeighter.startIndex = 0;
                        BeforeWeighter.IsWeightFin = false;
                        BeforeWeighter.Weight = 0;
                        BeforeWeighter.CurrWeight = 0;
                        BeforeWeighter.IsRunning = false;
                        BeforeWeighter.ServiceControl(true);
                        BeforeWeighter.IsRunning = true;
                    }
                    else
                    {
                        Logger.Info(string.Format("前称重条码为空"));
                    }
                    Thread.Sleep(200);
                    var sw = new Stopwatch();
                    sw.Start();
                    while (true)
                    {
                        if (BeforeWeighter.IsWeightFin == false)
                        {
                            if (sw.ElapsedMilliseconds > GlobalValues.WeightTimeout * 1000)
                            {
                                sw.Stop();
                                BeforeWeighter.Weight = BeforeWeighter.CurrWeight;
                                if (BeforeWeighter.IsRunning == true && BeforeWeighter.IsWeightFin == false)
                                {
                                    var msg = string.Format("前称重电子称超时", barcode);
                                    Logger.Error(msg);
                                }
                                BeforeWeighter.IsWeightFin = true;
                            }
                            Thread.Sleep(50);
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (BeforeWeighter.Weight <= 100)
                    {
                        Logger.Info(string.Format("前称称重结果异常。请检查 {0} {1}{2}", barcode, BeforeWeighter.Unit, BeforeWeighter.Weight));
                        return;
                    }
                    var weight = new BeforWeightFirst
                    {
                        ID = Guid.NewGuid(),
                        Index = 1,
                        Weight_OK = true,
                        BeforWeight_First = (float)BeforeWeighter.Weight,
                        OnceBeforWeight = 0,
                        OnceAfterWeight = 0,
                        LossVal = 0,
                        Code = barcode,
                        IsValidate = true,
                        ProductDate = DateTime.Now
                    };
                    short r = 1;
                    if (GlobalValues.EnableBeforeInjectCheck == true)
                    {
                        
                        if (GlobalValues.BeforeWeightMin <= weight.BeforWeight_First && GlobalValues.BeforeWeightMax >= weight.BeforWeight_First)
                        {
                            lock (locker)
                            {
                                r = r1;
                                plc.Write(DataType.DataBlock, DBNo, 82, r);//OK
                            }
                        }
                        else
                        {
                            lock (locker)
                            {
                                r = r2;
                                plc.Write(DataType.DataBlock, DBNo, 82, r);//NG
                                weight.Weight_OK = false;
                            }
                        }
                        Logger.Info(string.Format("前称重重量范围检查结果{0} {1} {2}~{3} {4}", weight.Code, weight.BeforWeight_First, GlobalValues.BeforeWeightMin, GlobalValues.BeforeWeightMax, r));
                    }

                    var retVal = string.Empty;

                    retVal = Lib.GetWeightBeforeInjectionC(weight.Code);
                    Logger.Info(string.Format("获取返工数据{0}", retVal));

                    var data = JsonConvert.DeserializeObject<OneWeightResult>(retVal);
                    var itemone = data.TestResultDetail.Where(s => s.ItemCode == "WeightRework").FirstOrDefault();
                    var itemtwo = data.TestResultDetail.Where(s => s.ItemCode == "WeightReworkTwo").FirstOrDefault();
                    var WeightRework = itemone == null ? 0 : itemone.Result;
                    var WeightReworkTwo = itemtwo == null ? 0 : itemtwo.Result;

                    if(r==1)
                    {
                        if (GlobalValues.OpType.ToUpper() == "EC")
                        {
                            Logger.Info("0");
                            var batt = CFDB.GetCodeFirst(barcode);
                            if (batt != null)
                            {
                                weight.OnceBeforWeight = batt.OnceBeforWeight;
                                weight.OnceAfterWeight = batt.OnceAfterWeight;
                                if (WeightRework != 0)
                                {
                                    weight.LossVal = WeightRework - weight.BeforWeight_First;
                                }
                                else
                                {
                                    weight.LossVal = batt.OnceAfterWeight - weight.BeforWeight_First;
                                }

                                #region 液矢量
                                short re = 1;
                                if (GlobalValues.VectorMin <= weight.LossVal && GlobalValues.VectorMax >= weight.LossVal)
                                {
                                    lock (locker)
                                    {
                                        re = r1;
                                        plc.Write(DataType.DataBlock, DBNo, 82, r1);//OK
                                    }
                                }
                                else
                                {
                                    lock (locker)
                                    {
                                        re = r2;
                                        plc.Write(DataType.DataBlock, DBNo, 82, r2);//NG
                                        weight.Weight_OK = false;
                                    }
                                }
                                Logger.Info(string.Format("前称重液矢量范围检查结果{0} {1} {2}~{3} {4}", weight.Code, weight.LossVal, GlobalValues.VectorMin, GlobalValues.VectorMax, re));
                                #endregion
                            }
                            else
                            {
                                Logger.Info(string.Format("从前扫码中查找{0} 信息失败", barcode));
                            }
                        }

                        #region 三次注液前称液矢量判断
                        if (GlobalValues.OpType.ToUpper() == "SC")
                        {
                            Logger.Info("0");
                            var batt = CFDB.GetCodeFirst(barcode);
                            if (batt != null)
                            {
                                weight.OnceBeforWeight = batt.OnceBeforWeight;
                                weight.OnceAfterWeight = batt.OnceAfterWeight;
                                if (WeightReworkTwo != 0)
                                {
                                    weight.LossVal = WeightReworkTwo - weight.BeforWeight_First;
                                }
                                else
                                {
                                    weight.LossVal = batt.TwoAfterWeight - weight.BeforWeight_First;
                                }

                                #region 液矢量
                                short re = 1;
                                if (GlobalValues.VectorMin <= weight.LossVal && GlobalValues.VectorMax >= weight.LossVal)
                                {
                                    lock (locker)
                                    {
                                        re = r1;
                                        plc.Write(DataType.DataBlock, DBNo, 82, r1);//OK
                                    }
                                }
                                else
                                {
                                    lock (locker)
                                    {
                                        re = r2;
                                        plc.Write(DataType.DataBlock, DBNo, 82, r2);//NG
                                        weight.Weight_OK = false;
                                    }
                                }
                                Logger.Info(string.Format("前称重液矢量范围检查结果{0} {1} {2}~{3} {4}", weight.Code, weight.LossVal, GlobalValues.VectorMin, GlobalValues.VectorMax, re));
                                #endregion
                            }
                            else
                            {
                                Logger.Info(string.Format("从前扫码中查找{0} 信息失败", barcode));
                            }
                        }
                        #endregion
                    }




                    if (GlobalValues.EnableVarInj)
                    {
                        Logger.Info("1");
                        var injVal = Math.Round((double)(GlobalValues.InjValTotalStd - (weight.BeforWeight_First - weight.OnceBeforWeight)), 2);
                        injVal = injVal < 0 ? 0 : injVal;
                        lock (locker)
                        {
                            plc.Write(DataType.DataBlock, DBNo, 44, (float)injVal);
                        }
                        Logger.Info(string.Format("传送注液量1 {0} {1}", barcode, (float)injVal));
                    }
                    else
                    {
                        Logger.Info("2");
                        lock (locker)
                        {
                            plc.Write(DataType.DataBlock, DBNo, 44, (float)Math.Round(GlobalValues.InjValStd));
                        }
                        Logger.Info(string.Format("传送注液量2 {0} {1}", barcode, (float)Math.Round(GlobalValues.InjValStd), 2));
                    }
                    Logger.Info("3");
                    var result = BFDB.Add2(weight);
                    if (result > 0)
                    {
                        Logger.Info(string.Format("前称重保存成功{0} {1}", barcode, BeforeWeighter.Weight));
                        Messenger.Default.Send<BeforWeightFirst>(weight, "SendBeforWeightFirst");
                    }
                    else
                    {
                        Logger.Info(string.Format("前称重保存失败{0} {1}", barcode, BeforeWeighter.Weight));
                    }
                    lock (locker)
                    {
                        plc.Write(DataType.DataBlock, DBNo, 76, r1);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Info(string.Format("{0} {1}", "BeforWeightHandle", ex));
            }
            finally
            {
                try
                {
                    lock (locker)
                    {
                        plc.Write(DataType.DataBlock, DBNo, 2, r0);
                    }
                }
                catch { }
            }
        }

        int barcodeBase = 184;
        int base1 = 20;
        int base2 = 32;
        /// <summary>
        /// 后称重
        /// </summary>
        public void AfterWeightHandle()
        {
            var injResult = r2;
            var barcode = "";
            var snowflake = "";
            try
            {
                lock (locker)
                {
                    plc.Write(DataType.DataBlock, DBNo, 4, r0);
                }
                if (IsConnected)
                {
                    byte[] barcodeByte = new byte[30];
                    short[] vals1 = new short[6];
                    float[] vals2 = new float[3];
                    float[] VacuumValue = new float[3];
                    float[] PPressureValue = new float[3];
                    float[] NPressureValue = new float[3];
                    //float[] vals2 = new float[3];

                    short? val3 = 0;
                    lock (locker)
                    {
                        // barcodeByte = plc.ReadBytes(DataType.DataBlock, DBNo, barcodeBase, 30);
                        vals1 = plc.Read(DataType.DataBlock, DBNo, base1, VarType.Int, 6) as short[];
                        vals2 = plc.Read(DataType.DataBlock, DBNo, base2, VarType.Real, 3) as float[];
                        val3 = plc.Read(DataType.DataBlock, DBNo, 86, VarType.Int, 1) as short?;
                        try
                        {
                            //真空度实际值
                            VacuumValue = plc.Read(DataType.DataBlock, DBNo, 226, VarType.Real, 2) as float[];
                            //正压实际值
                            PPressureValue = plc.Read(DataType.DataBlock, DBNo, 230, VarType.Real, 2) as float[];
                            //负压实际值
                            NPressureValue = plc.Read(DataType.DataBlock, DBNo, 234, VarType.Real, 2) as float[];
                        }catch (Exception ex)
                        {
                            Logger.Info(string.Format("获取真空实际值报错"+ex.ToString()));
                        }
                     

                        var snowflakeByte = plc.ReadBytes(DataType.DataBlock, DBNo, barcodeBase, 30);
                        snowflake = Kinlo.Model.Helper.ConvertByteToString(snowflakeByte);
                        var battsnowflake = CFDB.GetCodeFirstBySnowflake(snowflake);
                        barcode = battsnowflake.Code;
                    }
                    // barcode = Kinlo.Model.Helper.ConvertByteToString(barcodeByte);

                    if (!string.IsNullOrEmpty(barcode))
                    {
                        AfterWeighter.startIndex = 0;
                        AfterWeighter.IsWeightFin = false;
                        AfterWeighter.Weight = 0;
                        AfterWeighter.CurrWeight = 0;
                        AfterWeighter.IsRunning = false;
                        AfterWeighter.ServiceControl(true);
                        AfterWeighter.IsRunning = true;

                        Thread.Sleep(200);
                        var sw = new Stopwatch();
                        sw.Start();
                        while (true)
                        {
                            if (AfterWeighter.IsWeightFin == false)
                            {
                                if (sw.ElapsedMilliseconds > GlobalValues.WeightTimeout * 1000)
                                {
                                    sw.Stop();
                                    AfterWeighter.Weight = AfterWeighter.CurrWeight;
                                    if (AfterWeighter.IsRunning == true && AfterWeighter.IsWeightFin == false)
                                    {
                                        var msg = string.Format("后称重电子称超时", barcode);
                                        Logger.Error(msg);
                                    }
                                    AfterWeighter.IsWeightFin = true;
                                }
                                Thread.Sleep(50);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        Logger.Info(string.Format("后称重条码为空"));
                    }
                    if (AfterWeighter.Weight <= 100)
                    {
                        Logger.Info(string.Format("后称重结果异常。请检查 {0} {1} {1}", barcode, AfterWeighter.Unit, AfterWeighter.Weight));
                        return;
                    }
                    if (GlobalValues.Rework)
                    {
                        //返工
                        var batt = CFDB.GetReWork(barcode);
                        if (batt == null)
                        {
                            MessageBox.Show($"{barcode} 返工称重数据查找失败", "错误");
                            return;
                        }
                        batt.AftweWeight = AfterWeighter.Weight;
                        batt.ProductDate = DateTime.Now;
                        batt.RWorkOper = GlobalValues.EmpNo;

                        if (GlobalValues.OpType.ToUpper() == "EC" && GlobalValues.EnableVarInj)
                        {
                            batt.InjType = "二注返工";
                            batt.HoldInjValue = batt.AftweWeight - batt.OneBeforWeight;//    GlobalValues.InjValTotalMin;
                            batt.InjValue = (double)(batt.AftweWeight - batt.TwoBeforeWeight);
                            Logger.Info($"{(batt.HoldInjValue >= GlobalValues.InjValTotalMin && batt.HoldInjValue <= GlobalValues.InjValTotalMax)} {GlobalValues.InjValTotalMin} {GlobalValues.InjValTotalMax} {batt.HoldInjValue}");
                            if (batt.HoldInjValue >= GlobalValues.InjValTotalMin && batt.HoldInjValue <= GlobalValues.InjValTotalMax)
                            {
                                Logger.Info($"2");
                                injResult = r1;
                                batt.Result = 1; //合格
                            }
                            else if (batt.HoldInjValue < GlobalValues.InjValTotalMin)
                            {
                                injResult = r2;
                                batt.Result = 3; //少液
                            }
                            else
                            {
                                injResult = r2;
                                batt.Result = 2; //多液
                            }
                        }
                        else if (GlobalValues.OpType.ToUpper() == "EC" && GlobalValues.EnableVarInj)
                        {
                            batt.InjType = "三注返工";
                            batt.HoldInjValue = batt.AftweWeight - batt.OneBeforWeight;//    GlobalValues.InjValTotalMin;
                            batt.InjValue = (double)(batt.AftweWeight - batt.TwoBeforeWeight);
                            Logger.Info($"{(batt.HoldInjValue >= GlobalValues.InjValTotalMin && batt.HoldInjValue <= GlobalValues.InjValTotalMax)} {GlobalValues.InjValTotalMin} {GlobalValues.InjValTotalMax} {batt.HoldInjValue}");
                            if (batt.HoldInjValue >= GlobalValues.InjValTotalMin && batt.HoldInjValue <= GlobalValues.InjValTotalMax)
                            {
                                Logger.Info($"2");
                                injResult = r1;
                                batt.Result = 1; //合格
                            }
                            else if (batt.HoldInjValue < GlobalValues.InjValTotalMin)
                            {
                                injResult = r2;
                                batt.Result = 3; //少液
                            }
                            else
                            {
                                injResult = r2;
                                batt.Result = 2; //多液
                            }
                        }
                        else
                        {
                            batt.InjType = "一注返工";
                            batt.InjValue = (double)(batt.AftweWeight - batt.OneBeforWeight);
                            if (batt.InjValue >= GlobalValues.InjValMin && batt.InjValue <= GlobalValues.InjValMax)
                            {
                                injResult = r1;
                                batt.Result = 1; //合格
                            }
                            else if (batt.InjValue < GlobalValues.InjValTotalMin)
                            {
                                injResult = r2;
                                batt.Result = 3; //少液
                            }
                            else
                            {
                                injResult = r2;
                                batt.Result = 2; //多液
                            }
                        }
                        if (GlobalValues.EnableAfterInjectCheck == true)
                        {
                            if (!(batt.AftweWeight >= GlobalValues.AfterWeightMin && batt.AftweWeight <= GlobalValues.AfterWeightMax))
                            {
                                batt.Result = 4;
                                injResult = r2;
                                Logger.Info($"后称重重量不在范围内{batt.Barcode} {batt.BeforeWeight} {GlobalValues.AfterWeightMin}~{GlobalValues.AfterWeightMax}");
                            }
                        }

                        var code = CFDB.UpdateReWork(batt);
                        if (code > 0)
                            Logger.Info($"{batt.Barcode} 返工保存成功");
                        else
                        {
                            injResult = r2;
                            Logger.Info($"{batt.Barcode} 返工保存失败");
                        }

                        Task.Run(() =>
                        {
                            UploadDataToMes(batt);
                        });
                        Messenger.Default.Send<ReWork>(batt, "SendReWork");
                    }
                    else
                    {
                        var weight = new AfterWeightFirst
                        {
                            ID = Guid.NewGuid(),
                            Index = 1,
                            OnceBeforWeight = 0,
                            OnceAfterWeight = 0,
                            LossVal = 0,
                            BeforWeight_One = 0,
                            AfterWeight_One = 0,
                            InjectionNum_One = 0,
                            InjectionNum_Offset_One = 0,
                            AfterResult_One = "True",
                            BeforeResult_One = "True",
                            Result_One = "True",
                            Code = barcode,
                            IsValidate = true,
                            ProductDate = DateTime.Now,
                            BatchNo = GlobalValues.BatchNo,
                            BatchNo1 = GlobalValues.BatchNo1,
                            EmpNo = GlobalValues.EmpNo,
                            EquNo = GlobalValues.EquNo,
                            JDBatchNo = GlobalValues.JDBatchNo,
                            TrayNum = vals1[4],
                            TrayCol = vals1[3],
                            TrayIndex = vals1[2],
                            Loop = vals1[5],
                            PTime = vals1[0],
                            NTime = vals1[1],
                            Vacuum = vals2[0],
                            PPressure = vals2[1],
                            NPressure = vals2[2],
                            VacuumValue= VacuumValue[0],
                            PPressureValue = PPressureValue[0],
                            NPressureValue = NPressureValue[0],
                            InjValueLow = 0,
                            InjValueUp = 0,
                            JudgeType = false
                        };
                        if ((GlobalValues.OpType.ToUpper() == "EC" || GlobalValues.OpType.ToUpper() == "SC") && GlobalValues.EnableVarInj)
                        {
                            weight.InjValueLow = GlobalValues.InjValTotalMin;
                            weight.InjValueUp = GlobalValues.InjValTotalMax;
                        }

                        Logger.Info(string.Format("5 {0} {1} {2}", GlobalValues.OpType, weight.InjValueLow, weight.InjValueUp));
                        double? onceBeforeResult = 0;
                        double? onceAfterResult = 0;
                        double? lossVal = 0;
                        var beforeBatt = BFDB.GetBeforWeightByBarcode(barcode);
                        var codefirstBatt = CFDB.GetCodeFirst(barcode);
                        weight.StartTime = codefirstBatt != null ? codefirstBatt.ProductDate : new DateTime(1900, 01, 01, 00, 00, 00);

                        if (GlobalValues.OpType == "EC" || GlobalValues.OpType.ToUpper() == "SC")
                        {
                            if (beforeBatt != null)
                            {
                                onceBeforeResult = beforeBatt.OnceBeforWeight;
                                onceAfterResult = beforeBatt.OnceAfterWeight;
                                lossVal = beforeBatt.LossVal;
                                Logger.Info(string.Format("前称重数据查找成功 {0} 失液量为{1}", barcode, beforeBatt.LossVal));
                            }
                            else
                            {
                                Logger.Info(string.Format("前称重数据查找失败 {0}", barcode));
                            }
                        }
                        weight.ClassType = GetClassType(DateTime.Now);
                        weight.BeforWeight_One = (float)(beforeBatt == null ? 0 : beforeBatt.BeforWeight_First);
                        weight.BeforWeightTime = beforeBatt?.ProductDate ?? new DateTime(1900, 01, 01, 00, 00, 00);
                        weight.OnceBeforWeight = onceBeforeResult;
                        weight.OnceAfterWeight = onceAfterResult;
                        weight.LossVal = lossVal;
                        weight.AfterWeight_One = AfterWeighter.Weight;
                        var injVal = weight.AfterWeight_One - weight.BeforWeight_One;
                        double? injValTotal = 0;
                        weight.RetainVal = injValTotal;
                        weight.InjectionNum_One = injVal;
                        weight.Result_One = "True";
                        injResult = r1;
                        if (GlobalValues.OpType == "EC" && GlobalValues.EnableVarInj)
                        {
                            injValTotal = weight.AfterWeight_One - weight.OnceBeforWeight;
                            weight.RetainVal = injValTotal;

                            Logger.Info(string.Format("二次注液{0}启用变量注液的保液量实际值为 {1}", barcode, injValTotal));

                            if (!(injValTotal >= GlobalValues.InjValTotalMin && injValTotal <= GlobalValues.InjValTotalMax))
                            {
                                weight.InjectionNum_Offset_One = injValTotal - GlobalValues.InjValTotalStd;
                                weight.Result_One = "False";
                                injResult = r2;
                            }
                        }
                        else if (GlobalValues.OpType == "SC" && GlobalValues.EnableVarInj)
                        {
                            injValTotal = weight.AfterWeight_One - weight.OnceBeforWeight;
                            weight.RetainVal = injValTotal;

                            Logger.Info(string.Format("三次注液{0}启用变量注液的保液量实际值为 {1}", barcode, injValTotal));
                            if (!(injValTotal >= GlobalValues.InjValTotalMin && injValTotal <= GlobalValues.InjValTotalMax))
                            {
                                weight.InjectionNum_Offset_One = injValTotal - GlobalValues.InjValTotalStd;
                                weight.Result_One = "False";
                                injResult = r2;
                            }
                        }
                        else
                        {
                            if (!(injVal >= GlobalValues.InjValMin && injVal <= GlobalValues.InjValMax))
                            {
                                weight.InjectionNum_Offset_One = injVal - GlobalValues.InjValStd;
                                weight.Result_One = "False";
                                injResult = r2;
                            }
                        }

                        if (GlobalValues.EnableAfterInjectCheck == true)
                        {
                            short r = 1;
                            if (!(weight.AfterWeight_One >= GlobalValues.AfterWeightMin && weight.AfterWeight_One <= GlobalValues.AfterWeightMax))
                            {
                                r = r2;
                                weight.AfterResult_One = "False";
                                injResult = r2;
                                Logger.Info(string.Format("后称重重量不在范围内{0} {1} {2}~{3}", weight.Code, weight.AfterWeight_One, GlobalValues.AfterWeightMin, GlobalValues.AfterWeightMax));
                            }
                        }

                        if (val3 != null && val3 != 1)
                        {
                            weight.BeforeResult_One = "False";
                            injResult = r2;
                        }

                        var result = AFDB.Add2(weight);
                        if (result > 0)
                        {
                            Messenger.Default.Send<AfterWeightFirst>(weight, "SendAfterWeightFirst");
                            CFDB.Update(weight.Code);
                            BFDB.Update(weight.Code);
                            Interlocked.Increment(ref OutCount);
                            Logger.Info(string.Format("后称重保存成功{0} {1}", barcode, AfterWeighter.Weight));
                        }
                        else
                        {
                            injResult = r2;
                            Logger.Info(string.Format("后称重保存失败{0} {1}", barcode, AfterWeighter.Weight));
                        }

                        Task.Run(() =>
                        {
                            UploadDataToMes(weight);
                        });

                        CNTDB.UpdateBackCounter(OutCount, OKCount, NGCount);
                        Messenger.Default.Send<int>(OutCount, "SendOutCount");
                        Messenger.Default.Send<int>(OKCount, "SendOKCount");
                        Messenger.Default.Send<int>(NGCount, "SendNGCount");
                    }
                }
                lock (locker)
                {
                    plc.Write(DataType.DataBlock, DBNo, 84, injResult);//后称结果
                    plc.Write(DataType.DataBlock, DBNo, 78, r1);//后称完成
                }
            }
            catch (Exception ex)
            {
                Logger.Info(string.Format("{0} {1}", "AfterWeightHandle", ex.Message));
            }
            finally
            {
                try
                {
                    lock (locker)
                    {
                        plc.Write(DataType.DataBlock, DBNo, 4, r0);
                    }
                    Logger.Info(string.Format("后称重结果 {0} {1}", barcode, injResult));
                }
                catch { }
            }
        }
        int testType = 2;
        void UploadDataToMes(ReWork w)
        {
            try
            {
                var data = new SWDDataUpload();
                data.GroupCode = GlobalValues.GroupCode;
                data.GroupName = GlobalValues.GroupName;
                data.OperatorID = GlobalValues.EmpNo;
                data.MachineID = GlobalValues.EquNo;
                data.MoNumber = GlobalValues.MoNumber;
                data.TimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                data.TestResult = w.Result == 1 ? "0" : "1";
                data.ProductSn = w.Barcode;
                data.Z_ShipmentNo = "";
                data.F_ShipmentNo = "";
                data.ProductModel = GlobalValues.ProductModel;
                // data.Material.Add(new Material { MaterialNo = GlobalValues.BatchNo, MaterialLot = GlobalValues.BatchNo1 });

                var items = new List<WeightItem>();
                if (GlobalValues.OpType.ToUpper() == "YC"|| GlobalValues.OpType.ToUpper() == "EC"|| GlobalValues.OpType.ToUpper() == "SC")
                {

                    //var item41 = new WeightItem { ItemCode = "返工后称重（g）", Value = "" };
                    //var item42 = new WeightItem { ItemCode = "返工注液量（g）", Value = "" };
                    //var item43 = new WeightItem { ItemCode = "返工时间", Value = "" };
                    //var item44 = new WeightItem { ItemCode = "返工判定", Value = "" };
                    //var item45 = new WeightItem { ItemCode = "返工NG详情", Value = "" };

                    var item1 = new WeightItem { ItemCode = "返工后称重", Value = w.AftweWeight };
                    var item2 = new WeightItem { ItemCode = "返工注液量", Value = w.InjValue };
                    var item3 = new WeightItem { ItemCode = "返工时间", Value = w.ProductDate.ToString("yyyyy-MM-dd HH:mm:ss") };
                    //var item4 = new WeightItem { ItemCode = "返工员", Value = w.RWorkOper };
                    var ngDetail = w.Result != 1 ? w.Result == 2 ? "多液" : w.Result == 3 ? "少液" : w.Result == 4 ? "后称重量NG" : "" : "";
                    var item5 = new WeightItem { ItemCode = "返工NG详情", Value = ngDetail };
                    var item6 = new WeightItem { ItemCode = "返工判定", Value = (ngDetail==""?"合格": ngDetail) };

                    items.Add(item1);
                    items.Add(item2);
                    items.Add(item3);
                    //items.Add(item4);
                    items.Add(item5);
                    items.Add(item6);
                }
                //else if (GlobalValues.OpType.ToUpper() == "EC")
                //{
                //    var item1 = new WeightItem { ItemCode = "返工后称重", Value = w.AftweWeight };
                //    var item2 = new WeightItem { ItemCode = "二次注液量", Value = w.InjValue };
                //    var item6 = new WeightItem { ItemCode = "返工电解液保液量", Value = w.HoldInjValue };
                //    var item3 = new WeightItem { ItemCode = "返工时间", Value = w.ProductDate.ToString("yyyyy-MM-dd HH:mm:ss") };
                //    var item4 = new WeightItem { ItemCode = "返工员", Value = w.RWorkOper };
                //    var ngDetail = w.Result != 1 ? w.Result == 2 ? "多液" : w.Result == 3 ? "少液" : w.Result == 4 ? "后称重量NG" : "" : "";
                //    var item5 = new WeightItem { ItemCode = "返工NG详情", Value = ngDetail };

                //    items.Add(item1);
                //    items.Add(item2);
                //    items.Add(item3);
                //    items.Add(item4);
                //    items.Add(item5);
                //    items.Add(item6);
                //}
                //else if (GlobalValues.OpType.ToUpper() == "SC")
                //{
                //    var item1 = new WeightItem { ItemCode = "返工后称重", Value = w.AftweWeight };
                //    var item2 = new WeightItem { ItemCode = "二次注液量", Value = w.InjValue };
                //    var item6 = new WeightItem { ItemCode = "返工电解液保液量", Value = w.HoldInjValue };
                //    var item3 = new WeightItem { ItemCode = "返工时间", Value = w.ProductDate.ToString("yyyyy-MM-dd HH:mm:ss") };
                //    var item4 = new WeightItem { ItemCode = "返工员", Value = w.RWorkOper };
                //    var ngDetail = w.Result != 1 ? w.Result == 2 ? "多液" : w.Result == 3 ? "少液" : w.Result == 4 ? "后称重量NG" : "" : "";
                //    var item5 = new WeightItem { ItemCode = "返工NG详情", Value = ngDetail };

                //    items.Add(item1);
                //    items.Add(item2);
                //    items.Add(item3);
                //    items.Add(item4);
                //    items.Add(item5);
                //    items.Add(item6);
                //}
                else
                {
                    Logger.Info(string.Format("{0}返工上传MES 参数异常", w.Barcode));
                }
                data.TestData = items;
                var dataJson = JsonConvert.SerializeObject(data);
                Logger.Info(string.Format("{0}返工上传MES信息:{1}", w.Barcode, dataJson), false);
                if (GlobalValues.MesOnOff)
                {
                    var returnVal = Lib.TestDataGroupInfo(dataJson);
                    Logger.Info(string.Format("{0} 返工数据上传MES返回结果 {1}", w.Barcode, returnVal));
                    if (returnVal.StartsWith("NotConnect"))
                    {
                        Logger.Info(string.Format("{0} 返工数据上传MES失败", w.Barcode));
                        AddToMesRetran(w.Barcode, dataJson);
                    }
                    else
                    {
                        var result = JsonConvert.DeserializeObject<MesReturnResult>(returnVal);
                        if (result.Status.ToUpper().Contains("TRUE"))
                        {
                            Logger.Info(string.Format("{0} 返工数据上传MES成功", w.Barcode));
                        }
                        else
                        {
                            Logger.Info(string.Format("{0} 返工数据上传MES失败", w.Barcode));
                        }

                    }
                }
                else
                {
                    AddToMesRetran(w.Barcode, dataJson);
                }

            }
            catch (Exception ex)
            {
                Logger.Info(string.Format("{0} 上传数据到MES发生异常 {1}", w.Barcode, ex));
            }
        }

        void UploadDataToMes(AfterWeightFirst w)
        {
            try
            {
                var data = new SWDDataUpload();
                data.GroupCode = GlobalValues.GroupCode;
                data.GroupName = GlobalValues.GroupName;
                data.OperatorID = GlobalValues.EmpNo;
                data.MachineID = GlobalValues.EquNo;
                data.MoNumber = GlobalValues.MoNumber;
                data.TimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                data.TestResult = w.Result_One.ToUpper() == "TRUE" ? "0" : "1";//OK 传0 NG传1
                data.ProductSn = w.Code;
                data.Z_ShipmentNo = "";
                data.F_ShipmentNo = "";
                data.ProductModel = GlobalValues.ProductModel;
                data.Material.Add(new Material { MaterialNo = w.BatchNo, MaterialLot = w.BatchNo1 });

                #region MES最新参数属性
                #region 一注
                //var item1 = new WeightItem { ItemCode = "工序名", Value = "" };
                //var item2 = new WeightItem { ItemCode = "班次", Value = "" };
                //var item3 = new WeightItem { ItemCode = "制令单", Value = "" };
                //var item4 = new WeightItem { ItemCode = "组别", Value = "" };
                //var item5 = new WeightItem { ItemCode = "电芯条码", Value = "" };
                //var item6 = new WeightItem { ItemCode = "设备编号", Value = "" };
                //var item7 = new WeightItem { ItemCode = "注液工位", Value = "" };
                //var item8 = new WeightItem { ItemCode = "进站时间", Value = "" };
                //var item9 = new WeightItem { ItemCode = "出站时间", Value = "" };
                //var item10 = new WeightItem { ItemCode = "电解液料号", Value = "" };
                //var item11 = new WeightItem { ItemCode = "电解液批次号", Value = "" };
                //var item12 = new WeightItem { ItemCode = "电解液氢氟酸含量", Value = "" };
                //var item13 = new WeightItem { ItemCode = "电解液含水量", Value = "" };
                //var item14 = new WeightItem { ItemCode = "Hi-pot电阻上限值（MΩ）", Value = "" };
                //var item15 = new WeightItem { ItemCode = "Hi-pot电阻下限值（MΩ）", Value = "" };
                //var item16 = new WeightItem { ItemCode = "Hi-pot电阻实际值（MΩ）", Value = "" };
                //var item17 = new WeightItem { ItemCode = "Hi-pot电压设定值（V）", Value = "" };
                //var item18 = new WeightItem { ItemCode = "Hi-pot电压实际值（V）", Value = "" };
                //var item19 = new WeightItem { ItemCode = "Hi-pot测试时间设定值（S）", Value = "" };
                //var item20 = new WeightItem { ItemCode = "Hi-pot测试时间实际值（S）", Value = "" };
                //var item21 = new WeightItem { ItemCode = "一注电芯注液前重量上限值（g）", Value = "" };
                //var item22 = new WeightItem { ItemCode = "一注电芯注液前重量下限值（g）", Value = "" };
                //var item23 = new WeightItem { ItemCode = "一注电芯注液前重量实际值（g）", Value = "" };
                //var item24 = new WeightItem { ItemCode = "一注电芯注液后重量上限值（g）", Value = "" };
                //var item25 = new WeightItem { ItemCode = "一注电芯注液后重量下限值（g）", Value = "" };
                //var item26 = new WeightItem { ItemCode = "一注电芯注液后重量实际值（g）", Value = "" };
                //var item27 = new WeightItem { ItemCode = "一注注液量上限值（g）", Value = "" };
                //var item28 = new WeightItem { ItemCode = "一注注液量下限值（g）", Value = "" };
                //var item29 = new WeightItem { ItemCode = "一注注液量实际值（g）", Value = "" };
                //var item30 = new WeightItem { ItemCode = "一注注液前真空度设定值（kPa）", Value = "" };
                //var item31 = new WeightItem { ItemCode = "一注注液前真空度实际值（kPa）", Value = "" };
                //var item32 = new WeightItem { ItemCode = "一注注液正压设定值（kPa）", Value = "" };
                //var item33 = new WeightItem { ItemCode = "一注注液正压实际值（kPa）", Value = "" };
                //var item34 = new WeightItem { ItemCode = "一注单次正压时间设定值", Value = "" };
                //var item35 = new WeightItem { ItemCode = "一注单次正压时间实际值", Value = "" };
                //var item36 = new WeightItem { ItemCode = "一注注液负压设定值（kPa）", Value = "" };
                //var item37 = new WeightItem { ItemCode = "一注注液负压实际值（kPa）", Value = "" };
                //var item38 = new WeightItem { ItemCode = "一注单次负压时间设定值（S）", Value = "" };
                //var item39 = new WeightItem { ItemCode = "一注单次负压时间实际值（S）", Value = "" };
                //var item40 = new WeightItem { ItemCode = "一注循环次数", Value = "" };
                //var item41 = new WeightItem { ItemCode = "返工后称重（g）", Value = "" };
                //var item42 = new WeightItem { ItemCode = "返工注液量（g）", Value = "" };
                //var item43 = new WeightItem { ItemCode = "返工时间", Value = "" };
                //var item44 = new WeightItem { ItemCode = "返工判定", Value = "" };
                //var item45 = new WeightItem { ItemCode = "返工NG详情", Value = "" };
                //var item46 = new WeightItem { ItemCode = "作业员", Value = "" };
                //var item47 = new WeightItem { ItemCode = "NG详情", Value = "" };
                #endregion

                #region 二注
                //var item1 = new WeightItem { ItemCode = "工序名", Value = "" };
                //var item2 = new WeightItem { ItemCode = "班次", Value = "" };
                //var item3 = new WeightItem { ItemCode = "制令单", Value = "" };
                //var item4 = new WeightItem { ItemCode = "组别", Value = "" };
                //var item5 = new WeightItem { ItemCode = "电芯条码", Value = "" };
                //var item6 = new WeightItem { ItemCode = "设备编号", Value = "" };
                //var item7 = new WeightItem { ItemCode = "注液工位", Value = "" };
                //var item8 = new WeightItem { ItemCode = "进站时间", Value = "" };
                //var item9 = new WeightItem { ItemCode = "出站时间", Value = "" };
                //var item10 = new WeightItem { ItemCode = "电解液料号", Value = "" };
                //var item11 = new WeightItem { ItemCode = "电解液批次号", Value = "" };
                //var item12 = new WeightItem { ItemCode = "电解液氢氟酸含量", Value = "" };
                //var item13 = new WeightItem { ItemCode = "电解液含水量", Value = "" };
                //var item14 = new WeightItem { ItemCode = "二注电芯注液前重量上限值（g）", Value = "" };
                //var item15 = new WeightItem { ItemCode = "二注电芯注液前重量下限值（g）", Value = "" };
                //var item16 = new WeightItem { ItemCode = "二注电芯注液前重量实际值（g）", Value = "" };
                //var item17 = new WeightItem { ItemCode = "二注电芯注液后重量上限值（g）", Value = "" };
                //var item18 = new WeightItem { ItemCode = "二注电芯注液后重量下限值（g）", Value = "" };
                //var item19 = new WeightItem { ItemCode = "二注电芯注液后重量实际值（g）", Value = "" };
                //var item20 = new WeightItem { ItemCode = "二注注液量上限值（g）", Value = "" };
                //var item21 = new WeightItem { ItemCode = "二注注液量下限值（g）", Value = "" };
                //var item22 = new WeightItem { ItemCode = "二注注液量实际值（g）", Value = "" };
                //var item23 = new WeightItem { ItemCode = "重量校准上限值（g）", Value = "" };
                //var item24 = new WeightItem { ItemCode = "重量校准下限值（g）", Value = "" };
                //var item25 = new WeightItem { ItemCode = "重量校准实际值（g）", Value = "" };
                //var item26 = new WeightItem { ItemCode = "液矢量上限值（g）", Value = "" };
                //var item27 = new WeightItem { ItemCode = "液矢量下限值（g）", Value = "" };
                //var item28 = new WeightItem { ItemCode = "液矢量实际值（g）", Value = "" };
                //var item29 = new WeightItem { ItemCode = "保液量设定值（g）", Value = "" };
                //var item30 = new WeightItem { ItemCode = "保液量上限值（g）", Value = "" };
                //var item31 = new WeightItem { ItemCode = "保液量下限值（g）", Value = "" };
                //var item32 = new WeightItem { ItemCode = "保液量实际值（g）", Value = "" };
                //var item33 = new WeightItem { ItemCode = "二注注液前真空度设定值（kPa）", Value = "" };
                //var item34 = new WeightItem { ItemCode = "二注注液前真空度实际值（kPa）", Value = "" };
                //var item35 = new WeightItem { ItemCode = "二注注液正压设定值（kPa）", Value = "" };
                //var item36 = new WeightItem { ItemCode = "二注注液正压实际值（kPa）", Value = "" };
                //var item37 = new WeightItem { ItemCode = "二注正压时间设定值（S）", Value = "" };
                //var item38 = new WeightItem { ItemCode = "二注正压时间实际值（S）", Value = "" };
                //var item39 = new WeightItem { ItemCode = "二注注液负压设定值（kPa）", Value = "" };
                //var item40 = new WeightItem { ItemCode = "二注注液负压实际值（kPa）", Value = "" };
                //var item41 = new WeightItem { ItemCode = "二注负压时间设定值（S）", Value = "" };
                //var item42 = new WeightItem { ItemCode = "二注负压时间实际值（S）", Value = "" };
                //var item43 = new WeightItem { ItemCode = "二注循环次数", Value = "" };
                //var item44 = new WeightItem { ItemCode = "返工后称重（g）", Value = "" };
                //var item45 = new WeightItem { ItemCode = "返工注液量（g）", Value = "" };
                //var item46 = new WeightItem { ItemCode = "返工时间", Value = "" };
                //var item47 = new WeightItem { ItemCode = "返工判定", Value = "" };
                //var item48 = new WeightItem { ItemCode = "返工NG详情", Value = "" };
                //var item49 = new WeightItem { ItemCode = "作业员", Value = "" };
                //var item50 = new WeightItem { ItemCode = "NG详情", Value = "" };
                #endregion
                #region 三注
                //var item1 = new WeightItem { ItemCode = "工序名", Value = "" };
                //var item2 = new WeightItem { ItemCode = "班次", Value = "" };
                //var item3 = new WeightItem { ItemCode = "制令单", Value = "" };
                //var item4 = new WeightItem { ItemCode = "组别", Value = "" };
                //var item5 = new WeightItem { ItemCode = "电芯条码", Value = "" };
                //var item6 = new WeightItem { ItemCode = "设备编号", Value = "" };
                //var item7 = new WeightItem { ItemCode = "注液工位", Value = "" };
                //var item8 = new WeightItem { ItemCode = "进站时间", Value = "" };
                //var item9 = new WeightItem { ItemCode = "出站时间", Value = "" };
                //var item10 = new WeightItem { ItemCode = "电解液料号", Value = "" };
                //var item11 = new WeightItem { ItemCode = "电解液批次号", Value = "" };
                //var item12 = new WeightItem { ItemCode = "电解液氢氟酸含量", Value = "" };
                //var item13 = new WeightItem { ItemCode = "电解液含水量", Value = "" };
                //var item14 = new WeightItem { ItemCode = "三注电芯注液前重量上限值（g）", Value = "" };
                //var item15 = new WeightItem { ItemCode = "三注电芯注液前重量下限值（g）", Value = "" };
                //var item16 = new WeightItem { ItemCode = "三注电芯注液前重量实际值（g）", Value = "" };
                //var item17 = new WeightItem { ItemCode = "三注电芯注液后重量上限值（g）", Value = "" };
                //var item18 = new WeightItem { ItemCode = "三注电芯注液后重量下限值（g）", Value = "" };
                //var item19 = new WeightItem { ItemCode = "三注电芯注液后重量实际值（g）", Value = "" };
                //var item20 = new WeightItem { ItemCode = "三注注液量上限值（g）", Value = "" };
                //var item21 = new WeightItem { ItemCode = "三注注液量下限值（g）", Value = "" };
                //var item22 = new WeightItem { ItemCode = "三注注液量实际值（g）", Value = "" };
                //var item23 = new WeightItem { ItemCode = "液矢量上限值（g）", Value = "" };
                //var item24 = new WeightItem { ItemCode = "液矢量下限值（g）", Value = "" };
                //var item25 = new WeightItem { ItemCode = "液矢量实际值（g）", Value = "" };
                //var item26 = new WeightItem { ItemCode = "保液量设定值（g）", Value = "" };
                //var item27 = new WeightItem { ItemCode = "保液量上限值（g）", Value = "" };
                //var item28 = new WeightItem { ItemCode = "保液量下限值（g）", Value = "" };
                //var item29 = new WeightItem { ItemCode = "保液量实际值（g）", Value = "" };
                //var item30 = new WeightItem { ItemCode = "三注注液前真空度设定值（kPa）", Value = "" };
                //var item31 = new WeightItem { ItemCode = "三注注液前真空度实际值（kPa）", Value = "" };
                //var item32 = new WeightItem { ItemCode = "三注注液正压设定值（kPa）", Value = "" };
                //var item33 = new WeightItem { ItemCode = "三注注液正压实际值（kPa）", Value = "" };
                //var item34 = new WeightItem { ItemCode = "三注正压时间设定值（S）", Value = "" };
                //var item35 = new WeightItem { ItemCode = "三注正压时间实际值（S）", Value = "" };
                //var item36 = new WeightItem { ItemCode = "三注注液负压设定值（kPa）", Value = "" };
                //var item37 = new WeightItem { ItemCode = "三注注液负压实际值（kPa）", Value = "" };
                //var item38 = new WeightItem { ItemCode = "三注负压时间设定值（S）", Value = "" };
                //var item39 = new WeightItem { ItemCode = "三注负压时间实际值（S）", Value = "" };
                //var item40 = new WeightItem { ItemCode = "三注循环次数", Value = "" };
                //var item41 = new WeightItem { ItemCode = "返工后称重（g）", Value = "" };
                //var item42 = new WeightItem { ItemCode = "返工注液量（g）", Value = "" };
                //var item43 = new WeightItem { ItemCode = "返工时间", Value = "" };
                //var item44 = new WeightItem { ItemCode = "返工判定", Value = "" };
                //var item45 = new WeightItem { ItemCode = "返工NG详情", Value = "" };
                //var item46 = new WeightItem { ItemCode = "作业员", Value = "" };
                //var item47 = new WeightItem { ItemCode = "NG详情", Value = "" };
                #endregion

                #endregion
                var items = new List<WeightItem>();
                if (GlobalValues.OpType.ToUpper() == "YC")
                {

                    var item1 = new WeightItem { ItemCode = "工序名", Value = GlobalValues.GroupCode };
                    var item2 = new WeightItem { ItemCode = "班次", Value = w.ClassType };
                    var item3 = new WeightItem { ItemCode = "制令单", Value = GlobalValues.MoNumber };
                    var item4 = new WeightItem { ItemCode = "组别", Value = GlobalValues.GroupName };
                    var item5 = new WeightItem { ItemCode = "电芯条码", Value =w.Code };
                    var item6 = new WeightItem { ItemCode = "设备编号", Value = GlobalValues.EquNo };
                    var item7 = new WeightItem { ItemCode = "注液工位", Value = w.TrayNum };
                    var item8 = new WeightItem { ItemCode = "进站时间", Value = (w.StartTime != null) ? w.StartTime?.ToString("yyyy-MM-dd HH:mm:ss") : "1900-01-01 00:00:00" };
                    var item9 = new WeightItem { ItemCode = "出站时间", Value = w.ProductDate?.ToString("yyyy-MM-dd HH:mm:ss") };
                    var item10 = new WeightItem { ItemCode = "电解液料号", Value = GlobalValues.BatchNo };
                    var item11 = new WeightItem { ItemCode = "电解液批次号", Value = GlobalValues.BatchNo1 };
                    var item12 = new WeightItem { ItemCode = "电解液氢氟酸含量", Value = GlobalValues.DJYHydrofluoric };
                    var item13 = new WeightItem { ItemCode = "电解液含水量", Value = GlobalValues.DJYWater };

                    //var item14 = new WeightItem { ItemCode = "Hi-pot电阻上限值（MΩ）", Value = "" }; //没有上限，不传
                    var item15 = new WeightItem { ItemCode = "Hi-pot电阻下限值（MΩ）", Value = "" };
                    var item16 = new WeightItem { ItemCode = "Hi-pot电阻实际值（MΩ）", Value = "" };
                    var item17 = new WeightItem { ItemCode = "Hi-pot电压设定值（V）", Value = "" };
                    var item18 = new WeightItem { ItemCode = "Hi-pot电压实际值（V）", Value = "" };
                    var item19 = new WeightItem { ItemCode = "Hi-pot测试时间设定值（S）", Value = "" };
                    var item20 = new WeightItem { ItemCode = "Hi-pot测试时间实际值（S）", Value = "" };

                    var item21 = new WeightItem { ItemCode = "一注电芯注液前重量上限值（g）", Value = GlobalValues.BeforeWeightMax };
                    var item22 = new WeightItem { ItemCode = "一注电芯注液前重量下限值（g）", Value = GlobalValues.BeforeWeightMin };
                    var item23 = new WeightItem { ItemCode = "一注电芯注液前重量实际值（g）", Value = w.BeforWeight_One };
                    var item24 = new WeightItem { ItemCode = "一注电芯注液后重量上限值（g）", Value = GlobalValues.AfterWeightMax };
                    var item25 = new WeightItem { ItemCode = "一注电芯注液后重量下限值（g）", Value = GlobalValues.AfterWeightMin };
                    var item26 = new WeightItem { ItemCode = "一注电芯注液后重量实际值（g）", Value = w.AfterWeight_One };
                    var item27 = new WeightItem { ItemCode = "一注注液量上限值（g）", Value = GlobalValues.InjValMax };
                    var item28 = new WeightItem { ItemCode = "一注注液量下限值（g）", Value = GlobalValues.InjValMin };
                    var item29 = new WeightItem { ItemCode = "一注注液量实际值（g）", Value = w.InjectionNum_One };

                    var item30 = new WeightItem { ItemCode = "一注注液前真空度设定值（kPa）", Value = w.Vacuum };
                    var item31 = new WeightItem { ItemCode = "一注注液前真空度实际值（kPa）", Value = w.VacuumValue };

                    var item32 = new WeightItem { ItemCode = "一注注液正压设定值（kPa）", Value = w.PPressure };

                    var item33 = new WeightItem { ItemCode = "一注注液正压实际值（kPa）", Value = w.PPressureValue };

                    var item34 = new WeightItem { ItemCode = "一注单次正压时间设定值", Value = w.PTime };

                    var item35 = new WeightItem { ItemCode = "一注单次正压时间实际值", Value = w.PTime };

                    var item36 = new WeightItem { ItemCode = "一注注液负压设定值（kPa）", Value = w.NPressure };

                    var item37 = new WeightItem { ItemCode = "一注注液负压实际值（kPa）", Value = w.NPressureValue };

                    var item38 = new WeightItem { ItemCode = "一注单次负压时间设定值（S）", Value = w.NTime };

                    var item39 = new WeightItem { ItemCode = "一注单次负压时间实际值（S）", Value = w.NTime };
                    var item40 = new WeightItem { ItemCode = "一注循环次数", Value = w.Loop };

                    //var item41 = new WeightItem { ItemCode = "返工后称重（g）", Value = "" };
                    //var item42 = new WeightItem { ItemCode = "返工注液量（g）", Value = "" };
                    //var item43 = new WeightItem { ItemCode = "返工时间", Value = "" };
                    //var item44 = new WeightItem { ItemCode = "返工判定", Value = "" };
                    //var item45 = new WeightItem { ItemCode = "返工NG详情", Value = "" };

                    var item46 = new WeightItem { ItemCode = "作业员", Value = GlobalValues.EmpNo };
                    var item47 = new WeightItem { ItemCode = "NG详情", Value = w.Result_One.ToUpper() != "TRUE" ? (w.InjectionNum_Offset_One > 0 ? "偏多" : "偏少") : "" };


                    var f = CFDB.GetCodeFirst(w.Code);
                    var fdata = JsonConvert.SerializeObject(f);
                    Logger.Info(string.Format("{0}短路测试仪查询值:{1}", w.Code, fdata), false);
                    if (GlobalValues.TestType == 2)
                    {
                        if (f != null)
                        {
                            //var item14 = new WeightItem { ItemCode = "Hi-pot电阻上限值（MΩ）", Value = "" };
                            //var item15 = new WeightItem { ItemCode = "Hi-pot电阻下限值（MΩ）", Value = "" };
                            //var item16 = new WeightItem { ItemCode = "Hi-pot电阻实际值（MΩ）", Value = "" };
                            //var item17 = new WeightItem { ItemCode = "Hi-pot电压设定值（V）", Value = "" };
                            //var item18 = new WeightItem { ItemCode = "Hi-pot电压实际值（V）", Value = "" };
                            //var item19 = new WeightItem { ItemCode = "Hi-pot测试时间设定值（S）", Value = "" };
                            //var item20 = new WeightItem { ItemCode = "Hi-pot测试时间实际值（S）", Value = "" };


                            //item14.Value = f.R;
                            item15.Value = f.R;
                            item16.Value = f.Resistance;
                            item17.Value = f.VP;
                            item18.Value = f.Voltage;
                            item19.Value = f.ShortDuration;
                            item20.Value = f.ShortDuration;

                            items.Add(item15);
                            items.Add(item17);
                            items.Add(item19);
                            //items.Add(new WeightItem { ItemCode = "Hipot测试阻值", Value = f.Resistance });
                            //items.Add(new WeightItem { ItemCode = "VD1上升跌落电压", Value = f.Drop1 });
                            //items.Add(new WeightItem { ItemCode = "VD2持续跌落电压", Value = f.Drop2 });
                            //items.Add(new WeightItem { ItemCode = "VD3放电跌落电压", Value = f.Drop3 });
                            //items.Add(new WeightItem { ItemCode = "VP实际测量的电压值（V）", Value = f.Voltage });
                            //items.Add(new WeightItem { ItemCode = "TP实际测量的上升时间值(S)", Value = f.UpperTime });
                            //items.Add(new WeightItem { ItemCode = "VP设定测试电压(V)", Value = f.VP });
                            //items.Add(new WeightItem { ItemCode = "VD1设定百分比(%)", Value = f.VD1 });
                            //items.Add(new WeightItem { ItemCode = "VD2设定百分比(%)", Value = f.VD2 });
                            //items.Add(new WeightItem { ItemCode = "VD3设定百分比(%)", Value = f.VD3 });
                            //items.Add(new WeightItem { ItemCode = "TK设定脉冲保持时间(S)", Value = f.TK });
                            //items.Add(new WeightItem { ItemCode = "TF设定自由放电时间(S)", Value = f.TF });
                            //items.Add(new WeightItem { ItemCode = "RT设定测试时间(S)", Value = f.RT });
                            //items.Add(new WeightItem { ItemCode = "R设定电阻下限值", Value = f.R });
                            //items.Add(new WeightItem { ItemCode = "绝缘NG判断", Value = f.Result == true ? "OK" : "NG" });

                            var ngDetail = "";
                            if (!(f.Result == true))
                            {
                                //item12.Value = f.ProductDate?.ToString("yyyy-MM-dd HH:mm:ss") ?? "0";
                                //item16.Value = f.ProductDate?.ToString("yyyy-MM-dd HH:mm:ss");
                                //item20.Value = f.ProductDate?.ToString("yyyy-MM-dd HH:mm:ss") ?? "0";
                                item20.Value = f.RT;
                                item8.Value = f.ProductDate?.ToString("yyyy-MM-dd HH:mm:ss") ?? "0";

                                ngDetail += $"{(f.OpenResult == true ? "" : "开路NG ")}";
                                ngDetail += $"{(f.VoltageResult1 == true ? "" : "放电1结果NG ")}";
                                ngDetail += $"{(f.VoltageResult2 == true ? "" : "放电2结果NG ")}";
                                ngDetail += $"{(f.VPResult == true ? "" : "VP结果NG ")}";
                                ngDetail += $"{(f.Drop1Result == true ? "" : "VD1结果NG ")}";
                                ngDetail += $"{(f.Drop2Result == true ? "" : "VD2结果NG ")}";
                                ngDetail += $"{(f.Drop3Result == true ? "" : "VD3结果NG ")}";
                                ngDetail += $"{(f.TL_Result == true ? "" : "TL结果NG ")}";
                                ngDetail += $"{(f.TH_Result == true ? "" : "TH结果NG ")}";
                                ngDetail += $"{(f.ResistanceResult == true ? "" : "电阻测试结果NG ")}";
                                ngDetail += $"{(f.Result == true ? "" : "总结果NG ")}";
                            }
                            //item47.Value = item47.Value == "" ? $"{ngDetail}" : item47.Value;
                            items.Add(new WeightItem { ItemCode = "NG详情", Value = $"{ngDetail}" });
                        }
                    }
                    else
                    {
                        Logger.Info("1");
                        if (f != null)
                        {
                            Logger.Info("2");
                            //item10.Value = f.ShortValue ?? "0";
                            //item11.Value = f.ShortVoltage ?? "0";
                            //item12.Value = f.ProductDate?.ToString("yyyy-MM-dd HH:mm:ss") ?? "0";
                            //item16.Value = f.ProductDate?.ToString("yyyy-MM-dd HH:mm:ss");

                            //item14.Value = f.R;
                            item8.Value = f.ProductDate?.ToString("yyyy-MM-dd HH:mm:ss") ?? "0";

                            item15.Value = f.R;
                            item16.Value = f.ShortValue ?? "0";
                            item17.Value = f.VP;
                            item18.Value = f.ShortVoltage;
                            //item19.Value = f.ProductDate?.ToString("yyyy-MM-dd HH:mm:ss") ?? "0";
                            //item20.Value = f.ProductDate?.ToString("yyyy-MM-dd HH:mm:ss") ?? "0";
                            item19.Value = f.ShortDuration;
                            item20.Value = f.ShortDuration;

                            if (f.ShortResult != "PASS")
                                item47.Value = "短路NG";
                        }
                        else
                        {
                            Logger.Info(string.Format("1前扫码数据查找失败 {0}", w.Code));
                        }
                    }

                    #region 添加到列表
                    items.Add(item1);
                    items.Add(item2);
                    items.Add(item3);
                    items.Add(item4);
                    items.Add(item5);
                    items.Add(item6);
                    items.Add(item7);
                    items.Add(item8);
                    items.Add(item9);
                    items.Add(item10);
                    items.Add(item11);
                    items.Add(item12);
                    items.Add(item13);
                    //items.Add(item15);
                    items.Add(item16);
                    //items.Add(item17);
                    items.Add(item18);
                    //items.Add(item19);
                    items.Add(item20);
                    items.Add(item21);
                    items.Add(item22);
                    items.Add(item23);
                    items.Add(item24);
                    items.Add(item25);
                    items.Add(item26);
                    items.Add(item27);
                    items.Add(item28);
                    items.Add(item29);
                    items.Add(item30);
                    items.Add(item31);
                    items.Add(item32);
                    items.Add(item33);
                    items.Add(item34);
                    items.Add(item35);
                    items.Add(item36);
                    items.Add(item37);
                    items.Add(item38);
                    items.Add(item39);
                    items.Add(item40);
                    items.Add(item46);
                    items.Add(item47);
                    #endregion
                }
                else if (GlobalValues.OpType.ToUpper() == "EC")
                {
                    var item1 = new WeightItem { ItemCode = "工序名", Value = GlobalValues.GroupCode };
                    var item2 = new WeightItem { ItemCode = "班次", Value = w.ClassType };
                    var item3 = new WeightItem { ItemCode = "制令单", Value = GlobalValues.MoNumber };
                    var item4 = new WeightItem { ItemCode = "组别", Value = GlobalValues.GroupName };
                    var item5 = new WeightItem { ItemCode = "电芯条码", Value = w.Code };
                    var item6 = new WeightItem { ItemCode = "设备编号", Value = GlobalValues.EquNo };
                    var item7 = new WeightItem { ItemCode = "注液工位", Value = w.TrayNum };
                    var item8 = new WeightItem { ItemCode = "进站时间", Value = (w.StartTime != null) ? w.StartTime?.ToString("yyyy-MM-dd HH:mm:ss") : "1900-01-01 00:00:00" };
                    var item9 = new WeightItem { ItemCode = "出站时间", Value = w.ProductDate?.ToString("yyyy-MM-dd HH:mm:ss") };
                    var item10 = new WeightItem { ItemCode = "电解液料号", Value = GlobalValues.BatchNo };
                    var item11 = new WeightItem { ItemCode = "电解液批次号", Value = GlobalValues.BatchNo1 };
                    var item12 = new WeightItem { ItemCode = "电解液氢氟酸含量", Value = GlobalValues.DJYHydrofluoric };
                    var item13 = new WeightItem { ItemCode = "电解液含水量", Value = GlobalValues.DJYWater };

                    var item14 = new WeightItem { ItemCode = "二注电芯注液前重量上限值（g）", Value = GlobalValues.BeforeWeightMax };
                    var item15 = new WeightItem { ItemCode = "二注电芯注液前重量下限值（g）", Value = GlobalValues.BeforeWeightMin };
                    var item16 = new WeightItem { ItemCode = "二注电芯注液前重量实际值（g）", Value = w.BeforWeight_One };
                    var item17 = new WeightItem { ItemCode = "二注电芯注液后重量上限值（g）", Value = GlobalValues.AfterWeightMax };
                    var item18 = new WeightItem { ItemCode = "二注电芯注液后重量下限值（g）", Value = GlobalValues.AfterWeightMin };
                    var item19 = new WeightItem { ItemCode = "二注电芯注液后重量实际值（g）", Value = w.AfterWeight_One };
                    var item20 = new WeightItem { ItemCode = "二注注液量上限值（g）", Value = GlobalValues.InjValMax };
                    var item21 = new WeightItem { ItemCode = "二注注液量下限值（g）", Value = GlobalValues.InjValMin };
                    var item22 = new WeightItem { ItemCode = "二注注液量实际值（g）", Value = w.InjectionNum_One };

                    //var item23 = new WeightItem { ItemCode = "重量校准上限值（g）", Value = "" };
                    //var item24 = new WeightItem { ItemCode = "重量校准下限值（g）", Value = "" };
                    //var item25 = new WeightItem { ItemCode = "重量校准实际值（g）", Value = "" };

                    var item26 = new WeightItem { ItemCode = "液矢量上限值（g）", Value = GlobalValues.VectorMax };
                    var item27 = new WeightItem { ItemCode = "液矢量下限值（g）", Value = GlobalValues.VectorMin };
                    var item28 = new WeightItem { ItemCode = "液矢量实际值（g）", Value = w.LossVal };
                    var item29 = new WeightItem { ItemCode = "保液量设定值（g）", Value = GlobalValues.InjValTotalStd };
                    var item30 = new WeightItem { ItemCode = "保液量上限值（g）", Value = GlobalValues.InjValTotalMax };
                    var item31 = new WeightItem { ItemCode = "保液量下限值（g）", Value = GlobalValues.InjValTotalMin };
                    var item32 = new WeightItem { ItemCode = "保液量实际值（g）", Value = w.RetainVal };

                    var item33 = new WeightItem { ItemCode = "二注注液前真空度设定值（kPa）", Value = w.Vacuum };
                    var item34 = new WeightItem { ItemCode = "二注注液前真空度实际值（kPa）", Value = w.VacuumValue };
                    var item35 = new WeightItem { ItemCode = "二注注液正压设定值（kPa）", Value = w.PPressure };
                    var item36 = new WeightItem { ItemCode = "二注注液正压实际值（kPa）", Value = w.PPressureValue };
                    var item37 = new WeightItem { ItemCode = "二注正压时间设定值（S）", Value = w.PTime };
                    var item38 = new WeightItem { ItemCode = "二注正压时间实际值（S）", Value = w.PTime };
                    var item39 = new WeightItem { ItemCode = "二注注液负压设定值（kPa）", Value = w.NPressure };
                    var item40 = new WeightItem { ItemCode = "二注注液负压实际值（kPa）", Value = w.NPressureValue };
                    var item41 = new WeightItem { ItemCode = "二注负压时间设定值（S）", Value = w.NTime };
                    var item42 = new WeightItem { ItemCode = "二注负压时间实际值（S）", Value = w.NTime };
                    var item43 = new WeightItem { ItemCode = "二注循环次数", Value = w.Loop };

                    //var item44 = new WeightItem { ItemCode = "返工后称重（g）", Value = "" };
                    //var item45 = new WeightItem { ItemCode = "返工注液量（g）", Value = "" };
                    //var item46 = new WeightItem { ItemCode = "返工时间", Value = "" };
                    //var item47 = new WeightItem { ItemCode = "返工判定", Value = "" };
                    //var item48 = new WeightItem { ItemCode = "返工NG详情", Value = "" };

                    var item49 = new WeightItem { ItemCode = "作业员", Value = GlobalValues.EmpNo };
                    var item50 = new WeightItem { ItemCode = "NG详情", Value = w.Result_One.ToUpper() != "TRUE" ? (w.InjectionNum_Offset_One > 0 ? "偏多" : "偏少") : "" };



                    var codeBatt = CFDB.GetCodeFirst(w.Code);
                    if (codeBatt != null)
                    {
                        //投入时间
                        item8.Value = codeBatt.ProductDate?.ToString("yyyy-MM-dd HH:mm:ss");
                    }
                    else
                    {
                        Logger.Info(string.Format("1前扫码数据查找失败 {0}", w.Code));
                    }
                    #region 添加到列表
                    items.Add(item1);
                    items.Add(item2);
                    items.Add(item3);
                    items.Add(item4);
                    items.Add(item5);
                    items.Add(item6);
                    items.Add(item7);
                    items.Add(item8);
                    items.Add(item9);
                    items.Add(item10);
                    items.Add(item11);
                    items.Add(item12);
                    items.Add(item13);
                    items.Add(item14);
                    items.Add(item15);
                    items.Add(item16);
                    items.Add(item17);
                    items.Add(item18);
                    items.Add(item19);
                    items.Add(item20);
                    items.Add(item21);
                    items.Add(item22);
                    //items.Add(item23);
                    //items.Add(item24);
                    //items.Add(item25);
                    items.Add(item26);
                    items.Add(item27);
                    items.Add(item28);
                    items.Add(item29);
                    items.Add(item30);
                    items.Add(item31);
                    items.Add(item32);
                    items.Add(item33);
                    items.Add(item34);
                    items.Add(item35);
                    items.Add(item36);
                    items.Add(item37);
                    items.Add(item38);
                    items.Add(item39);
                    items.Add(item40);
                    items.Add(item41);
                    items.Add(item42);
                    items.Add(item43);
                    items.Add(item49);
                    items.Add(item50);
                    #endregion
                }
                else if (GlobalValues.OpType.ToUpper() == "SC")
                {
                    var item1 = new WeightItem { ItemCode = "工序名", Value = GlobalValues.GroupCode };
                    var item2 = new WeightItem { ItemCode = "班次", Value = w.ClassType };
                    var item3 = new WeightItem { ItemCode = "制令单", Value = GlobalValues.MoNumber };
                    var item4 = new WeightItem { ItemCode = "组别", Value = GlobalValues.GroupName };
                    var item5 = new WeightItem { ItemCode = "电芯条码", Value = w.Code };
                    var item6 = new WeightItem { ItemCode = "设备编号", Value = GlobalValues.EquNo };
                    var item7 = new WeightItem { ItemCode = "注液工位", Value = w.TrayNum };
                    var item8 = new WeightItem { ItemCode = "进站时间", Value = (w.StartTime != null) ? w.StartTime?.ToString("yyyy-MM-dd HH:mm:ss") : "1900-01-01 00:00:00" };
                    var item9 = new WeightItem { ItemCode = "出站时间", Value = w.ProductDate?.ToString("yyyy-MM-dd HH:mm:ss") };
                    var item10 = new WeightItem { ItemCode = "电解液料号", Value = GlobalValues.BatchNo };
                    var item11 = new WeightItem { ItemCode = "电解液批次号", Value = GlobalValues.BatchNo1 };
                    var item12 = new WeightItem { ItemCode = "电解液氢氟酸含量", Value = GlobalValues.DJYHydrofluoric };
                    var item13 = new WeightItem { ItemCode = "电解液含水量", Value = GlobalValues.DJYWater };

                    var item14 = new WeightItem { ItemCode = "三注电芯注液前重量上限值（g）", Value = GlobalValues.BeforeWeightMax };
                    var item15 = new WeightItem { ItemCode = "三注电芯注液前重量下限值（g）", Value = GlobalValues.BeforeWeightMin };
                    var item16 = new WeightItem { ItemCode = "三注电芯注液前重量实际值（g）", Value = w.BeforWeight_One };
                    var item17 = new WeightItem { ItemCode = "三注电芯注液后重量上限值（g）", Value = GlobalValues.AfterWeightMax };
                    var item18 = new WeightItem { ItemCode = "三注电芯注液后重量下限值（g）", Value = GlobalValues.AfterWeightMin };
                    var item19 = new WeightItem { ItemCode = "三注电芯注液后重量实际值（g）", Value = w.AfterWeight_One };
                    var item20 = new WeightItem { ItemCode = "三注注液量上限值（g）", Value = GlobalValues.InjValMax };
                    var item21 = new WeightItem { ItemCode = "三注注液量下限值（g）", Value = GlobalValues.InjValMin };
                    var item22 = new WeightItem { ItemCode = "三注注液量实际值（g）", Value = w.InjectionNum_One };
                    var item23 = new WeightItem { ItemCode = "液矢量上限值（g）", Value = GlobalValues.VectorMax };
                    var item24 = new WeightItem { ItemCode = "液矢量下限值（g）", Value = GlobalValues.VectorMin };
                    var item25 = new WeightItem { ItemCode = "液矢量实际值（g）", Value = w.LossVal };
                    var item26 = new WeightItem { ItemCode = "保液量设定值（g）", Value = GlobalValues.InjValTotalStd };
                    var item27 = new WeightItem { ItemCode = "保液量上限值（g）", Value = GlobalValues.InjValTotalMax };
                    var item28 = new WeightItem { ItemCode = "保液量下限值（g）", Value = GlobalValues.InjValTotalMin };
                    var item29 = new WeightItem { ItemCode = "保液量实际值（g）", Value = w.RetainVal };

                    var item30 = new WeightItem { ItemCode = "三注注液前真空度设定值（kPa）", Value = w.Vacuum };
                    var item31 = new WeightItem { ItemCode = "三注注液前真空度实际值（kPa）", Value = w.VacuumValue };
                    var item32 = new WeightItem { ItemCode = "三注注液正压设定值（kPa）", Value = w.PPressure };
                    var item33 = new WeightItem { ItemCode = "三注注液正压实际值（kPa）", Value = w.PPressureValue };
                    var item34 = new WeightItem { ItemCode = "三注正压时间设定值（S）", Value = w.PTime };
                    var item35 = new WeightItem { ItemCode = "三注正压时间实际值（S）", Value = w.PTime };
                    var item36 = new WeightItem { ItemCode = "三注注液负压设定值（kPa）", Value = w.NPressure };
                    var item37 = new WeightItem { ItemCode = "三注注液负压实际值（kPa）", Value = w.NPressureValue };
                    var item38 = new WeightItem { ItemCode = "三注负压时间设定值（S）", Value = w.NTime };
                    var item39 = new WeightItem { ItemCode = "三注负压时间实际值（S）", Value = w.NTime };
                    var item40 = new WeightItem { ItemCode = "三注循环次数", Value = w.Loop };

                    //var item41 = new WeightItem { ItemCode = "返工后称重（g）", Value = "" };
                    //var item42 = new WeightItem { ItemCode = "返工注液量（g）", Value = "" };
                    //var item43 = new WeightItem { ItemCode = "返工时间", Value = "" };
                    //var item44 = new WeightItem { ItemCode = "返工判定", Value = "" };
                    //var item45 = new WeightItem { ItemCode = "返工NG详情", Value = "" };

                    var item46 = new WeightItem { ItemCode = "作业员", Value = GlobalValues.EmpNo };
                    var item47 = new WeightItem { ItemCode = "NG详情", Value = w.Result_One.ToUpper() != "TRUE" ? (w.InjectionNum_Offset_One > 0 ? "偏多" : "偏少") : "" };
                    #region 添加到列表
                    items.Add(item1);
                    items.Add(item2);
                    items.Add(item3);
                    items.Add(item4);
                    items.Add(item5);
                    items.Add(item6);
                    items.Add(item7);
                    items.Add(item8);
                    items.Add(item9);
                    items.Add(item10);
                    items.Add(item11);
                    items.Add(item12);
                    items.Add(item13);
                    items.Add(item14);
                    items.Add(item15);
                    items.Add(item16);
                    items.Add(item17);
                    items.Add(item18);
                    items.Add(item19);
                    items.Add(item20);
                    items.Add(item21);
                    items.Add(item22);
                    items.Add(item23);
                    items.Add(item24);
                    items.Add(item25);
                    items.Add(item26);
                    items.Add(item27);
                    items.Add(item28);
                    items.Add(item29);
                    items.Add(item30);
                    items.Add(item31);
                    items.Add(item32);
                    items.Add(item33);
                    items.Add(item34);
                    items.Add(item35);
                    items.Add(item36);
                    items.Add(item37);
                    items.Add(item38);
                    items.Add(item39);
                    items.Add(item40);
                    items.Add(item46);
                    items.Add(item47);
                    #endregion

                }
                else
                {
                    Logger.Info(string.Format("上传MES 参数异常 {0}", w.Code));
                }
                data.TestData = items;
                var dataJson = JsonConvert.SerializeObject(data);
                Logger.Info(string.Format("{0}上传MES信息:{1}", w.Code, dataJson), false);
                if (GlobalValues.MesOnOff)
                {
                    var returnVal = Lib.TestDataGroupInfo(dataJson);
                    Logger.Info(string.Format("{0} 称重数据上传MES返回结果 {1}", w.Code, returnVal));
                    if (returnVal.StartsWith("NotConnect"))
                    {
                        Logger.Info(string.Format("{0} 称重数据上传MES失败", w.Code));
                        AddToMesRetran(w.Code, dataJson);
                    }
                    else
                    {
                        var result = JsonConvert.DeserializeObject<MesReturnResult>(returnVal);
                        if (result.Status.ToUpper().Contains("TRUE"))
                        {
                            Logger.Info(string.Format("{0} 称重数据上传MES成功", w.Code));
                        }
                        else
                        {
                            Logger.Info(string.Format("{0} 称重数据上传MES失败", w.Code));
                        }

                    }
                    //    var result = JsonConvert.DeserializeObject<MesReturnResult>(returnVal);
                    //if (result.Status.ToUpper().Contains("TRUE"))
                    //{
                    //    Logger.Info(string.Format("{0} 称重数据上传MES成功",w.Code));
                    //}else if(returnVal.StartsWith("NotConnect")){

                    //    Logger.Info(string.Format("{0} 称重数据上传MES失败", w.Code));
                    //    AddToMesRetran(w.Code, dataJson);
                    //}
                    //else
                    //{
                    //    Logger.Info(string.Format("{0} 称重数据上传MES失败", w.Code)); 
                    //}
                }
                else
                {
                    AddToMesRetran(w.Code, dataJson);
                }

            }
            catch (Exception ex)
            {
                Logger.Info(string.Format("{0} 上传数据到MES发生异常 {1}", w.Code, ex));
            }
        }
        void AddToMesRetran(string barcode, string dataJson)
        {
            var retranToMes = new RetranToMesInfo();
            retranToMes.ID = Guid.NewGuid();
            retranToMes.Barcode = barcode;
            retranToMes.Date = DateTime.Now;
            retranToMes.Message = dataJson;
            retranToMes.IsUpload = false;
            retranToMes.RetranCount++;
            retranToMes.UploadDate = DateTime.Now;
            var code = AFDB.AddToMesRetran(retranToMes);
            if (code > 0)
            {
                Logger.Info(string.Format("{0} 重传MES数据保存成功", barcode));
            }
            else
            {
                Logger.Info(string.Format("{0} 重传MES数据保存失败 {1}", barcode, dataJson));
            }
        }


        //string signal1 = "MOHM:AUTO:DCLear OFF\r\n";
        //byte[] shortStart = Encoding.Default.GetBytes(":START\r\n");
        //byte[] shortStop = Encoding.Default.GetBytes(":Stop\r\n");
        //byte[] readResult = Encoding.Default.GetBytes(":MEASure:RESult?\r\n");
        //byte[] buf = new byte[1024];

        string signal1 = "MOHM:AUTO:DCLear OFF\r\n";
        string shortStart = ":START\r\n";

        //短路测试值， 电阻查询
        string resistance = ":MEASure?\r\n";

        string voltage = ":VOLTage?\r\n";
        string testTimer = ":TIMer?\r\n";
        string shortStop = ":Stop\r\n";
        byte[] buf = new byte[1024];


        int testCount = 0;
        int shortTestBase = 124;
        public void ShortCicuteTestHandle()
        {
Loop:
            if (GlobalValues.Rework)
            {
                lock (locker)
                {
                    plc.Write(DataType.DataBlock, DBNo, 74, r1);
                    plc.Write(DataType.DataBlock, DBNo, 72, r1);
                    plc.Write(DataType.DataBlock, DBNo, 8, r0);
                }
                return;
            }
            string barcode = "";
            string snowflake = "";
            try
            {
                lock (locker)
                {
                    plc.Write(DataType.DataBlock, DBNo, 8, r0);
                    //var barcodeByte = plc.ReadBytes(DataType.DataBlock, DBNo, shortTestBase, 30);
                    //barcode = Kinlo.Model.Helper.ConvertByteToString(barcodeByte);

                    var snowflakeByte = plc.ReadBytes(DataType.DataBlock, DBNo, shortTestBase, 30);
                    snowflake = Kinlo.Model.Helper.ConvertByteToString(snowflakeByte);
                    var battsnowflake = CFDB.GetCodeFirstBySnowflake(snowflake);
                    barcode = battsnowflake.Code;
                }
                if (IsCheckBarcode)
                {
                    if (!Regex.IsMatch(barcode, StrRegex))
                    {
                        Log(string.Format("短路测试 {0} 不符合条码过滤规则", barcode));
                    }
                }
                if (!serialPort.IsOpen)
                {
                    if (!SerialPortInit())
                    {
                        lock (locker)
                        {
                            plc.Write(DataType.DataBlock, DBNo, 74, r2);
                            plc.Write(DataType.DataBlock, DBNo, 72, r1);
                        }
                        Logger.Info(string.Format("端口打开失败 发送短路测试完成 测试结果{0} {1}", barcode, r2));
                        return;
                    }
                }
                serialPort.Write(signal1);
                try
                {
                    while (true)
                    {
                        serialPort.ReadTimeout = 100;
                        serialPort.Read(buf, 0, buf.Length);
                    }
                }
                catch { }

                serialPort.ReadTimeout = SerialPortTimeout;
                serialPort.Write(shortStart);
                var resultStr = serialPort.ReadLine();
                Log(string.Format("{0}短路测试结果 {1}", barcode, resultStr.Trim()));
                var resultByte = Encoding.Default.GetBytes(resultStr);
                int seq = 0;
                int.TryParse(Encoding.Default.GetString(resultByte, 0, 4).Trim(), out seq);
                var val = Encoding.Default.GetString(resultByte, 6, 5).Trim();
                var unit = Encoding.Default.GetString(resultByte, 12, 4).Trim();
                var result = Encoding.Default.GetString(resultByte, 20, resultByte.Length - 20).Trim();
                Log(string.Format("{0} {1} {2}", val, unit, result));
                string volResult = "";
                string timerResult = "";
                string resistanceValue = "";
                try
                {
                    serialPort.Write(voltage);
                    volResult = serialPort.ReadLine().Trim();
                    serialPort.Write(testTimer);
                    timerResult = serialPort.ReadLine().Trim().Split(' ').LastOrDefault();

                    //serialPort.Write(resistance);
                    //resistanceValue = serialPort.ReadLine().Trim();
                    
                }
                catch { }


                short testVal = r2;
                switch (result.Trim())
                {
                    case "PASS":
                        testCount = 0;
                        var w = CFDB.GetCodeFirst(barcode);
                        if (w != null)
                        {
                            w.ShortVoltage = volResult;
                            w.ShortDuration = timerResult;
                            w.ShortResult = result.Trim();
                            w.ShortResult2 = "true";
                            w.ShortUnit = unit;
                            //w.ShortValue = resistanceValue;
                            Decimal de;
                            if (Decimal.TryParse(val, System.Globalization.NumberStyles.Any, null, out de))
                            {
                                w.ShortValue = de.ToString();
                            }
                            w.ProductDate = DateTime.Now;
                            var code = CFDB.UpdateCodeFirst(w);
                            if (code > 0)
                            {
                                testVal = r1;
                                Log(string.Format("短路测试 {0}保存成功 ", barcode));

                            }
                            else
                            {
                                testVal = r2;
                                Log(string.Format("短路测试 {0}保存失败 ", barcode));
                            }
                            Messenger.Default.Send<CodeFirst>(w, "SendShortCicuteTest");
                        }
                        else
                        {
                            testVal = r2;
                            Log(string.Format("前扫码中没找到对应的电池条码{0} ", barcode));
                        }
                        //lock (locker)
                        //{
                        //    plc.Write(DataType.DataBlock, DBNo, 74, testVal);
                        //    plc.Write(DataType.DataBlock, DBNo, 72, r1);
                        //}
                        //Logger.Info(string.Format("发送短路测试完成 测试结果{0} {1}", barcode, testVal));
                        break;
                    case "NOCOMP":
                        if (testCount < 1)
                        {
                            Log(string.Format("{0}测试结果NOCOMP重测", barcode));
                            testCount++;
                            goto Loop;
                            //ShortCicuteTestHandle();
                            //break;
                        }
                        break;
                    default:
                        testVal = r2;
                        testCount = 0;
                        var w1 = CFDB.GetCodeFirst(barcode);
                        if (w1 != null)
                        {
                            w1.ShortVoltage = volResult;
                            w1.ShortDuration = timerResult;
                            w1.ShortResult = result.Trim();
                            w1.ShortResult2 = "false";
                            w1.ShortUnit = unit;
                            Decimal de;
                            if (Decimal.TryParse(val, System.Globalization.NumberStyles.Any, null, out de))
                            {
                                w1.ShortValue = de.ToString();
                            }
                            w1.ProductDate = DateTime.Now;
                            var code = CFDB.UpdateCodeFirst(w1);
                            if (code > 0)
                            {
                                Logger.Info(string.Format("短路测试 {0}保存成功1 ", barcode));
                            }
                            else
                            {
                                Logger.Info(string.Format("短路测试 {0}保存失败1 ", barcode));
                            }
                            Messenger.Default.Send<CodeFirst>(w1, "SendShortCicuteTest");
                        }
                        else
                        {
                            Logger.Info(string.Format("没能在前扫码中没找到对应的电池条码{0} ", barcode));
                        }
                        break;
                }

                lock (locker)
                {
                    plc.Write(DataType.DataBlock, DBNo, 74, testVal);
                    plc.Write(DataType.DataBlock, DBNo, 72, r1);
                }
                Logger.Info(string.Format("发送短路测试完成 测试结果{0} {1}", barcode, testVal));

            }
            catch (Exception ex)
            {
                lock (locker)
                {
                    plc.Write(DataType.DataBlock, DBNo, 74, r2);
                    plc.Write(DataType.DataBlock, DBNo, 72, r1);
                }
                Logger.Info(string.Format("短路测试异常:{0} {1}", barcode, ex));
            }
            finally
            {
                try
                {
                    lock (locker)
                    {
                        plc.Write(DataType.DataBlock, DBNo, 8, r0);
                    }
                }
                catch { }
            }
        }


        /// <summary>
        /// 新短路测试仪流程
        /// </summary>
        public void NewShortCicuteTestHandle()
        {
            Logger.Info("test 2");
            if (GlobalValues.Rework)
            {
                lock (locker)
                {
                    plc.Write(DataType.DataBlock, DBNo, 74, r1);
                    plc.Write(DataType.DataBlock, DBNo, 72, r1);
                    plc.Write(DataType.DataBlock, DBNo, 8, r0);
                }
                return;
            }
            string barcode = "";
            try
            {
                lock (locker)
                {
                    plc.Write(DataType.DataBlock, DBNo, 8, r0);
                    var barcodeByte = plc.ReadBytes(DataType.DataBlock, DBNo, shortTestBase, 30);
                    barcode = Helper.ConvertByteToString(barcodeByte);
                }
                if (IsCheckBarcode)
                {
                    if (!Regex.IsMatch(barcode, StrRegex))
                    {
                        Log(string.Format("短路测试 {0} 不符合条码过滤规则", barcode));
                    }
                }
                if (!shortCircuit.IsOpen)
                {
                    if (!shortCircuit.Conncet())
                    {
                        lock (locker)
                        {
                            plc.Write(DataType.DataBlock, DBNo, 74, r2);
                            plc.Write(DataType.DataBlock, DBNo, 72, r1);
                        }
                        Logger.Info(string.Format("短路测试仪打开失败 发送短路测试完成 测试结果{0} {1}", barcode, r2));
                        return;
                    }
                }
                short testVal = r2;
                Result startResult = shortCircuit.Start(0x02);
                Thread.Sleep(1000);
                if (startResult.IsSuccess)
                {
                    Result<RJ6902R0X59> result = shortCircuit.GetTestDataAndResult(0x02);
                    Thread.Sleep(500);
                    var result2 = shortCircuit.GetWaveInfo(0x02);
                    if (result.IsSuccess)
                    {
                        Logger.Info($"【短路测试】1条码:{barcode} 读取测试结果成功,测试结果{(result.Content.Result.Value ? "通过" : "不通过")}");
                        Logger.Info($"【短路测试】1条码:{barcode} {JsonConvert.SerializeObject(result)}");
                        CodeFirst code = CFDB.GetCodeFirst(barcode);
                        if (code != null)
                        {
                            code.Drop1 = result.Content.Drop1;
                            code.Drop1Result = result.Content.Drop1Result;
                            code.Drop2 = result.Content.Drop2;
                            code.Drop2Result = result.Content.Drop2Result;
                            code.Drop3 = result.Content.Drop3;
                            code.Drop3Result = result.Content.Drop3Result;
                            code.ResidueVoltage = result.Content.ResidueVoltage;
                            code.ResidueVoltageResult = result.Content.ResidueVoltageResult;
                            code.VoltageResult1 = result.Content.VoltageResult1;
                            code.VoltageResult2 = result.Content.VoltageResult2;
                            code.VPResult = result.Content.VPResult;
                            code.UpperTime = result.Content.UpperTime;
                            code.TL_Result = result.Content.TLResult;
                            code.TH_Result = result.Content.THResult;
                            code.OpenResult = result.Content.OpenResult;
                            code.Voltage = result.Content.Voltage;
                            code.Resistance = result.Content.Resistance;
                            code.ResistanceResult = result.Content.ResistanceResult;
                            code.Result = result.Content.Result;
                            code.VP = result2.Content.Val3;
                            code.VD1 = result2.Content.Val6 / 10.0f;
                            code.VD2 = result2.Content.Val7 / 10.0f;
                            code.VD3 = result2.Content.Val8 / 10.0f;
                            code.R = result2.Content.Val12;
                            code.TF = result2.Content.Val5;
                            code.TK = result2.Content.Val4;
                            code.RT = result2.Content.Val11 / 10;
                            code.ProductDate = DateTime.Now;
                            int number = CFDB.UpdateCodeFirstNew(code);
                            testVal = number > 0 && code.Result != null && code.Result.Value ? r1 : r2;
                            Logger.Info($"【短路测试】条码:{barcode} 短路测试结果{(code.Result.Value ? "OK" : "NG")}保存{(number > 0 ? "成功" : "失败")}");
                            Messenger.Default.Send(code, "SendShortCicuteTest");
                        }
                        else
                        {
                            testVal = r2;
                            Logger.Info(string.Format("没能在前扫码中没找到对应的电池条码{0} ", barcode));
                        }
                    }
                    else
                    {
                        Logger.Info("7");
                        lock (locker)
                        {
                            plc.Write(DataType.DataBlock, DBNo, 74, r2);
                            plc.Write(DataType.DataBlock, DBNo, 72, r1);
                        }
                        Logger.Info($"【短路测试】读取测试结果失败:{result.ErroMessage}");
                        return;
                    }
                }
                else
                {
                    testVal = r2;
                    Logger.Info($"【短路测试】条码:{barcode} 短路测试仪启动失败,失败信息:{startResult.ErroMessage}");
                }

                lock (locker)
                {
                    plc.Write(DataType.DataBlock, DBNo, 74, testVal);//发送测试结果
                    plc.Write(DataType.DataBlock, DBNo, 72, r1);//发送完成信号
                }
                Logger.Info(string.Format("发送短路测试完成 测试结果{0} {1}", barcode, testVal));
            }
            catch (Exception ex)
            {
                lock (locker)
                {
                    plc.Write(DataType.DataBlock, DBNo, 74, r2);
                    plc.Write(DataType.DataBlock, DBNo, 72, r1);
                }
                Logger.Info(string.Format("短路测试异常:{0} {1}", barcode, ex));
            }
            finally
            {
                try
                {
                    lock (locker)
                    {
                        plc.Write(DataType.DataBlock, DBNo, 8, r0);//命令复位
                    }
                    Logger.Info(shortCircuit.DisConncet() ? "短路测试关闭成功" : "短路测试仪关闭失败");//关闭短路测试仪
                }
                catch { }
            }
        }

        void BeforeWeightClearHandle()
        {
            try
            {
                BeforeWeighter.ClearZero();
                Logger.Info("前称清零完成");
            }
            catch (Exception ex)
            {
                Logger.Info(string.Format("前称清零异常:{0}", ex.Message));
            }
            finally
            {
                try
                {
                    lock (locker)
                    {
                        plc.Write(DataType.DataBlock, DBNo, 10, r0);
                        plc.Write(DataType.DataBlock, DBNo, 90, r1);
                    }
                }
                catch { }
            }
        }
        void AfterWeightClearHandle()
        {
            try
            {
                AfterWeighter.ClearZero();
                Logger.Info("后称清零完成");

            }
            catch (Exception ex)
            {
                Logger.Info(string.Format("后称清零异常:{0}", ex.Message));
            }
            finally
            {
                try
                {
                    lock (locker)
                    {
                        plc.Write(DataType.DataBlock, DBNo, 12, r0);
                        plc.Write(DataType.DataBlock, DBNo, 92, r1);
                    }
                }
                catch { }
            }
        }

        bool SerialPortInit()
        {
            try
            {
                serialPort = new SerialPort(PortName, BaudRate, Parity, DataBits, StopBits)
                {
                    ReadTimeout = SerialPortTimeout,
                    WriteTimeout = SerialPortTimeout
                };
                serialPort.Open();
                return true;
            }
            catch (Exception ex)
            {
                Logger.Info(string.Format("测试仪打开失败", ex.Message));
                return false;
            }
        }
        public void Start()
        {
            Logger.Info("开始");
            timer.Enabled = true;
        }
        public void Stop()
        {
            Logger.Info("停止");
            timer.Enabled = false;
        }
        public void Log(string msg)
        {
            Logger.Info(msg);
        }
        //public void UploadWeight2(AfterWeightFirst ww)
        //{
        //    var client = new TestWebServices.ServiceReference1.BisWebServiceSoapClient();
        //    try
        //    { 
        //       var w = new UplodWeight2()
        //        {
        //            barcode = ww.Code,
        //            weight = ww.AfterWeight_One,
        //            createBy = GlobalValues.EmpNo,
        //            DevNo = MachineCode,
        //            state = ww.Result_One.ToUpper() == "TRUE" ? "OK" : "NG",
        //            StationNo = StationNo,
        //            WorkFlowNo = WorkFlowNo,
        //            WorkFlowOrder = WorkFlowOrder,
        //            weightBefore = ww.BeforWeight_One,
        //            weightDif = ww.InjectionNum_One,
        //            ClassType = GetClassType((DateTime)ww.ProductDate)
        //        };

        //        var s = client.UplodWeight_2(w.barcode, w.weight ?? 0, w.WorkFlowNo, w.createBy, w.StationNo, w.ClassType,
        //            w.WorkFlowOrder ?? 0, w.DevNo, w.state, w.weightBefore ?? 0, w.weightDif ?? 0);
        //        Logger.Info(string.Format("数据上传结果{0} {1} {2}", w.barcode, s,w.state));
        //        var result = JsonConvert.DeserializeObject<UplodWeight2Response>(s);
        //        if (result.code == "200")
        //        {
        //            Logger.Info(string.Format("数据上传成功{0} {1}", w.barcode, result.msg));
        //            var code = AFDB.UpdateUplodWeight2Status(w.barcode);
        //            if (code > 0)
        //            {
        //                Logger.Info(string.Format("更新{0}数据上传状态成功", w.barcode));
        //            }
        //            else
        //            {
        //                Logger.Info(string.Format("更新{0}数据上传状态失败", w.barcode));
        //            } 
        //        }
        //        else
        //        {
        //            Logger.Info(string.Format("数据上传失败{0} {1}", w.barcode, result.msg));
        //        }  
        //    }
        //    catch (Exception ex)
        //    {
        //        Logger.Info(string.Format("数据上传发生异常{0} {1}", ww.Code, ex.Message));
        //    }
        //    finally
        //    {
        //        client.Close();
        //    }
        //}

        public string GetClassType(DateTime time)
        {
            try
            {
                if (time.Hour >= 8 && time.Hour < 20)
                {
                    return "白班";
                }
                else
                {
                    return "晚班";
                }
            }
            catch (Exception)
            {
                return "";
            }
        }

        public string PackTestDataGroupInfo()
        {
            return "";
        }
    }
}
